将带有名称和标签的 .csv 文件读取到 R 中

标签 r label read.table hmisc

我有一个 .csv 文件,我需要将其读入 R。第一行包含名称(例如 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 文件并访问这两个值吗?

最佳答案

不确定您是否同意将标签作为单独的向量,但这里有一个想法。假设您的文件名为 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")

关于将带有名称和标签的 .csv 文件读取到 R 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973610/

相关文章:

R 使用管道运算符时的条件评估 %>%

R dplyr : Use the function as a string in one column on the next column

java - 从单独的线程内更新标签

c# - C# 中的打开文件对话框

delphi - 如何在窗体上绘制透明文字?

R:读取不带文件头的文件

r - 如何读取不同分隔符的数据?

r - 如何在R中选择分组数据的特定部分?

r - 无法将 ggproto 对象添加在一起

read.table 函数用于读取 R 中不完整的数据