2

我有一个需要读入 R 的 .csv 文件。第一行包含名称(例如 BFI1、BFI2、CAQ2),第二行包含我也想在 R 中访问的问题(例如“我喜欢参加派对”)。前两个之后的每一行对应一个参与者。

我希望能够访问 R 中的代码和文本(例如,用于grep访问一项调查中的所有问题,并在需要时查看项目文本。我需要数字响应为数字。

BFI1, BFI2, CAQ1, CAQ2
Likes to read, Enjoys Parties, Is Nervous, Loves Books
3, 7, 1, 4
4, 5, 3, 3

我想阅读此内容,以便可以访问名称(第 1 行)或文本(可能作为标签)。我看过Hmisc包装,但它们的标签功能似乎有限。

有没有办法读取这个 .csv 文件并访问这两个值?

4

4 回答 4

2

不确定您是否可以将标签作为单独的向量,但这是一个想法。假设你的文件名是x.txt

## set up an argument list for scan() - just to avoid repetition
scanArgs <- list(
    file = "x.txt", what = "", nlines = 1, sep = ",", strip.white = TRUE
)

## read the data with no header and add the first line as names
df <- setNames(
    read.table("x.txt", skip = 2, sep = ","), 
    do.call(scan, scanArgs)
)
#   BFI1 BFI2 CAQ1 CAQ2
# 1    3    7    1    4
# 2    4    5    3    3

## make the label vector
labels <- setNames(do.call(scan, c(scanArgs, skip = 1)), names(df))
#            BFI1             BFI2             CAQ1             CAQ2 
# "Likes to read" "Enjoys Parties"     "Is Nervous"    "Loves Books" 

所以中的元素labels对应于中的列,df并且列是数字的。

请注意,它x.txt是用

txt <- 'BFI1, BFI2, CAQ1, CAQ2
Likes to read, Enjoys Parties, Is Nervous, Loves Books
3,7,1,4
4,5,3,3'
writeLines(txt, "x.txt")
于 2015-01-15T22:09:43.493 回答
1

您可以使用 nrows 和 skip 参数或 read.csv

nameFile <- "data.csv"

# read the first two lines
vectorNames <- read.csv(nameFile, nrows = 1)
vectorDescription <- read.csv(nameFile, nrows = 1, skip = 1)

# read the data
dfIn <- read.csv(nameFile, skip = 2)
names(dfIn) <- vectorNames
于 2015-01-15T22:00:03.160 回答
1

基于 Michelle Usuelli 的回答和 Rich Scriven 更正,您可以编写以下函数:

read_csv_with_labels <- function(fileName)
{
 library(Hmisc)

 # read the first two lines
 varNames <- read.csv(fileName, nrows = 1, stringsAsFactors = FALSE, header = FALSE)
 varLabels <- read.csv(fileName, nrows = 1, stringsAsFactors = FALSE, header = TRUE)

 # read the data
 df <- read.csv(fileName, skip = 2)

 # assign variable names and labels to the dataframe
 names(df) <- varNames
 label(df) <- varLabels 

 return(df)
}

我认为这应该包含在 read.csv 和 read_csv 的基本功能中。

于 2017-05-31T16:01:55.870 回答
0

@Richard Scriven 我使用了您的代码并使用包跟进了它

library(Hmisc)
y=data.frame(temp=rep(NA,nrow(df)))  
for (i in 1:length(labels)){  
x=df[,i]  
label(x)=labels[i]   
y[names(df)[i]]=x  
}  
y$temp=NULL  
y  
#  BFI1 BFI2 CAQ1 CAQ2
# 1    3    7    1    4
# 2    4    5    3    3
label(y)
#            BFI1             BFI2             CAQ1             CAQ2 
# "Likes to read" "Enjoys Parties"     "Is Nervous"    "Loves Books" 
于 2015-01-16T04:45:49.643 回答