[英]Iterating through variables (columns) in a dataframe in R
I am a total beginner in R, so this might be an obvious question. 我是R语言的初学者,所以这可能是一个显而易见的问题。 I have a dataframe with 129 variables, some numeric, some string.
我有一个包含129个变量,一些数字和一些字符串的数据框。 Basically, I am trying to loop through each variable to calculate the mean/mode(depending on the variable), standard dev (if applicable), and frequency, and have it some sort of nice package I could export.
基本上,我试图遍历每个变量以计算均值/众数(取决于变量),标准dev(如果适用)和频率,并使其具有某种我可以导出的好程序包。 I have tried using a for loop, but I can only get it to go through rows, not columns.
我已经尝试过使用for循环,但是我只能让它遍历行而不是列。 Anyone have any suggestions?
有人有什么建议吗?
Thanks!! 谢谢!!
You can use a for-loop across columns too. 您也可以跨列使用for循环。
# Considering only 8 rows and using numeric and character cols for demonstration
iris_new = iris[1:8,]
iris_new$Species = as.character(iris_new$Species)
for(i in iris_new){
print(i)
}
[1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0
[1] 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4
[1] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5
[1] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2
[1] "setosa" "setosa" "setosa" "setosa" "setosa" "setosa" "setosa" "setosa"
colnames(my_dataframe)
yields a vector containing the column names of 'my_dataframe'. colnames(my_dataframe)
产生一个包含列名“ my_dataframe”的向量。 You can iterate over the elements, here's an example printing the first element of each column: 您可以遍历元素,这是打印每列第一个元素的示例:
for (the_column in colnames(m))
{
print(my_dataframe[,c(the_column)][1])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.