如何读取可变名称的列表并在R中的函数中替换它们?
我想编写一个读取可变名称列表的脚本。这些变量名称是data.frame中的一些列标题。然后,我想做一个前面的循环,以对数据中的指定变量执行各种操作。框架并因此以命名的文件打印,但是我不知道如何进行必要的变量替换。数据帧有1260列和2600行。并非所有列都是连续变量,有些是因素,描述符等,因此我使用Varlist选择要分析的列。
我在
#Example script scaled down for simplicity
Dataset <- iris
varlist <- data.frame("Sepal.Length", "Sepal.Width", "Petal.Length")
for (i in 1:length(varlist)){
model <- lm(SOMETHINGHERE_i ~ Petal.Width, data = Dataset)
printing <- data.frame(SOMETHINGHERE_i = model$coefficients['Petal.Width'])
write.csv(printing,paste0("C://Users/Me/Desktop/",SOMETHINGHERE_i,"/",SOMETHINGHERE_i,"PetalWidthSlope.csv"))
}
我上面链接的页面说我应该放置varlist [i]
,它适用于保存部分,但该模型给出了错误:
错误:意外'='在: “模型&lt; - lm(varlist [i] 〜petal.width,data = dataset) 打印&lt; - data.frame(varlist [i] =“
)
它也建议使用sapply(dataset [varlist],function)
,但我不知道如何将其应用于lm
,但是无论如何,如果我尝试使用`sapply(dataset [varlist],均值),它将打印:
中的错误[。默认值
(数据集,varlist):无效的下标类型'list'
我该怎么办?
提前致谢!
I would like to write a script that reads a list of variable names. These variable names are some of the column headers in a data.frame. Then I want to do a for-loop to execute various operations on the specified variables in the data.frame and print them in accordingly named files, but I can't figure out how to do the necessary variable substitution. The data.frame has 1260 columns and 2600 rows. Not all columns are continuous variables, some are factors, descriptors, etc., so I use the varlist to pick which columns I want to analyze.
I found basically the same question in https://stat.ethz.ch/pipermail/r-help/2010-February/228752.html, but the author's suggestions don't work for me.
#Example script scaled down for simplicity
Dataset <- iris
varlist <- data.frame("Sepal.Length", "Sepal.Width", "Petal.Length")
for (i in 1:length(varlist)){
model <- lm(SOMETHINGHERE_i ~ Petal.Width, data = Dataset)
printing <- data.frame(SOMETHINGHERE_i = model$coefficients['Petal.Width'])
write.csv(printing,paste0("C://Users/Me/Desktop/",SOMETHINGHERE_i,"/",SOMETHINGHERE_i,"PetalWidthSlope.csv"))
}
The page I linked above says that I should put varlist[i]
and it works for the saving part, but the model gives error:
Error: unexpected '=' in:
" model <- lm(varlist[i] ~ Petal.Width, data = Dataset)
printing <- data.frame(varlist[i] ="
It also suggests using sapply(Dataset[varlist], function)
, but I don't know how to apply it to lm
, but regardless, if I try with `sapply(Dataset[varlist], mean), it prints:
Error in
[.default
(Dataset, varlist) : invalid subscript type 'list'
What should I do?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
as.formula
将文本转换为有效的R公式。 (但是当您发现时,您不能将R公式用作宏。)我还将varlist
项目用作循环变量而不是顺序整数。我现在在桌面上还有3个文件:
You can use
as.formula
to convert text to valid R formulas. (But as you are discovering you cannot use R formulas as macros.) I also used just thevarlist
items as the loop variables rather than sequential integers.I now have 3 more files on my Desktop: