r - 在 R 中为每一行拆分逗号分隔的字符串
问题描述
我在 R 中有一个包含 3000 行的表(名为“df”)。
在每一行的“TestResults”列中,有一串数字,由逗号分隔(例如,5、10、1、3...)。
我想在“df”中创建一个名为“TestValue1”的新列,它只包含在“TestResults”中找到的字符串中的第一个数字(因此,在示例行中,“TestResults”下的值为“5”。
这是我正在运行的代码:
for (i in 1:nrow(df)) {
rname=rownames(df)[i]
a <- as.numeric(unlist(strsplit(df[rname, "TestResults"],",")))
df[rname, "TestValue1"] <- a[1]
}
我收到的错误消息是:
Error in strsplit(df[rname, ("TestResults"))], :
non-character argument
但是,当我运行 : 时class(df$TestResults)
,我收到 :
[1] "character"
所以数字字符串是一个字符
(即使没有调用 as.numeric 函数,此错误也成立)
非常感谢您的帮助!
解决方案
该gsub
函数似乎适用于我生成的示例数据。希望它适用于您的数据!
#Created example data
res<-data.frame((rbind(("5, 10, 1, 3"),("4,3,2,10"), ("8,21,0,8"))))
names(res)<-"TestResults"
res$TestResults<-(as.character(res$TestResults))
#Run gsub
res$TestValue1<-gsub(",.*", "\\1", res$TestResults)
#See results
res
输出结果:
TestResults TestValue1
1 5, 10, 1, 3 5
2 4,3,2,10 4
3 8,21,0,8 8