[英]Write each data.table column to separate text files in R
I have a read a csv file into a data.table that is as follows: 我已经将csv文件读入data.table,如下所示:
Cat1 Cat2 Cat3 Country file_name
1: A E B Canada first
2: C B India Second
3: C Canada third
4: B Ireland Fourth
5: C A India fifth
6: A C F Canada Sixth
I am using following code to write the contents of each row to a separate text file: 我正在使用以下代码将每一行的内容写入单独的文本文件:
lapply(1:nrow(df), function(i) write.table(df[i], file= paste0("./TextFiles/", df[i, file_name], ".txt"), row.names = F, col.names = F, quote = F))
The output I am getting right now is as follows for "Sixth.txt" (for example): 我现在得到的输出如下所示,例如“ Sixth.txt”:
A C F Canada Sixth
However, I want the text to be as follows: 但是,我希望文本如下:
Cat1
A
Cat2
C
Cat3
F
Country
Canada
Is there a way to get this output without nesting a lot of lapply ? 有没有办法在不嵌套很多lapply的情况下获得此输出?
Trying the code: 尝试代码:
lapply(df, function(i) i)
gives the output: 给出输出:
$Cat1
[1] "A" "C" "C" "B" "C" "A"
$Cat2
[1] "E" "B" "" "" "A" "C"
$Cat3
[1] "B" "" "" "" "" "F"
$Country
[1] "Canada" "India" "Canada" "Ireland" "India" "Canada"
$file_name
[1] "first" "Second" "third" "Fourth" "fifth" "Sixth"
So, I have a feeling it is possible to get the names of the columns before the content and also to insert lines before each column entry. 因此,我觉得可以在内容之前获取列的名称,也可以在每个列条目之前插入行。 However, I am unable to find a way to do it. 但是,我找不到解决方法。
Use apply()
function to make each row to a list and then output it using sink()
inside for
loop. 使用apply()
函数将每一行制作到一个列表中,然后在for
循环中使用sink()
将其输出。 Then check your working directory to see the files File1.txt
, File2.txt
, File3.txt
and File4.txt
. 然后检查你的工作目录中看到文件File1.txt
, File2.txt
, File3.txt
和File4.txt
。 Filename can be extracted using strsplit()
and can be added to the file output using Result[[i]]$file_name
可以使用strsplit()
提取文件名,并可以使用Result[[i]]$file_name
将其添加到文件输出中
library(data.table)
df <- data.frame(a=1:4,b=9:12,c=3:6,d=0:3)
df <- data.table(df)
df
# a b c d
# 1: 1 9 3 0
# 2: 2 10 4 1
# 3: 3 11 5 2
# 4: 4 12 6 3
Result = apply(df,1,as.list)
for(i in 1:length(Result)){
sink(paste("File",i,".txt",sep=""))
Result[[i]]$file_name <- strsplit(paste("File",i,".txt",sep=""),"\\.")[[1]][1]
print(Result[[i]])
sink()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.