在 for 循环中写入多个文件 [英] Write many files in a for loop

查看:51
本文介绍了在 for 循环中写入多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的样本数据

df <- data.frame(name = rep(letters[1:7], each = 24), salary = runif(24*7, 100, 200))

我想把每个名字和他们的薪水分开

I wanted to separate each name with their salaries

lst <- tapply(df$salary, df$name, matrix, nrow = 4, byrow = TRUE)

现在我想将所有这 7 个矩阵写入 7 个不同的文本文件,它一次仅适用于一个矩阵.我试图放入一个 for 循环但不起作用

Now I want to write all these 7 matrices to 7 different text files, It is working only for a single matrix at a time. I tried to put in a for loop but is not working

for (i in 1:7)
{
write.table(lst[i], ".txt", col.names = FALSE, row.names = FALSE, sep = "\t", quote = FALSE)
}

有人可以建议在 for 循环中进行修改吗?

Can any one suggest for the modifications in the for loop?

推荐答案

给定你的 lst,下面将把它写成一系列名称与 名称相同的 TXT 文件lst,加上.txt:

Given your lst, the following will write this out to a series of TXT files with names equal to the name of lst, plus .txt:

lapply(names(lst),
       function(x, lst) write.table(lst[[x]], paste(x, ".txt", sep = ""),
                                    col.names=FALSE, row.names=FALSE, sep="\t", 
                                    quote=FALSE),
       lst)

要修改您的 for() 循环,请尝试:

To modify your for() loop, try:

for(i in seq_along(lst)) {
    write.table(lst[[i]], paste(names(lst)[i], ".txt", sep = ""), 
                col.names = FALSE, row.names = FALSE, sep = "\t", quote = FALSE)
}

问题是试图或假设 R 会为您粘贴文件名.

The problem was trying to or assuming R would paste together the filenames for you.

这篇关于在 for 循环中写入多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆