使用R中第二列的匹配值将列值写入文件
我在R中有一个数据帧使用R中第二列的匹配值将列值写入文件,r,R,我在R中有一个数据帧df,它有几个列,其中columnA和columnB在这里很有趣: columnA columnB ab1 'This is a string' ts4 'This is another string' pq9 'This is yet another string' 我想将字符串写入文件,并在文件名中包含匹配的columnA值 sapply(df$columnB, function(x){ write.table(x,
df
,它有几个列,其中columnA
和columnB
在这里很有趣:
columnA columnB
ab1 'This is a string'
ts4 'This is another string'
pq9 'This is yet another string'
我想将字符串写入文件,并在文件名中包含匹配的columnA
值
sapply(df$columnB, function(x){
write.table(x,
file = paste("matching_column_a_",
which(x == df$columnB, arr.ind = T),
".txt",
sep = ""),
col.names = FALSE,
row.names = FALSE,
append=F,
sep = "\t",
quote = FALSE)
})
然而,我的try只给出了行的索引,但这对我没有用处
有没有一种方法可以将其写入一个文件,其中文件名与
列b
字符串的匹配类似于匹配列a\u ab1.txt
,…a\u ts4.txt
,等等?我们可以遍历行序列,使用该索引将列值子集,以便将其写入不同的文件
lapply(seq_len(nrow(df1)), function(i)
write.table(df1$columnB,
file = paste0("matching_column_a_", df1$columnA[i], ".txt"),
col.names = FALSE,
row.names = FALSE,
append=FALSE,
sep = "\t",
quote = FALSE) )
为什么不通过
columnA
循环它,即lappy(df1$columnA,
。您是否将每一行作为不同的数据集编写?此外,您可以循环通过行序列。每一行都将是一个新文件是的(我知道这不整洁,但我需要它用于python中的文件后续文本分析)。在这种情况下,请按行顺序循环,lappy(seq(nrow(df1)),function(i),…)
谢谢!是否要将此作为其他可能有类似问题的人的答案提交?