我正在 R 中学习 for循环。我试图弄清楚如何在中的变量中的中的 data.frame 。我在Stackoverflow中调查了几个例子,例如 Q1 , Q2 , Q3 ,但没有一个对我正在寻找的东西有用!
I am learning the for loop in R. I am trying to figure it out how to make a for loop in an specific variable in data.frame. I looked into several example in stackoverflow such as Q1, Q2, Q3 but none is useful of what I am looking for!
作为使用 mtcars 数据集的示例,请说明我想执行循环到:
As an example using the mtcars dataset , let say I want to perform a for loop to:
查看 cyl 并为 cyl 4,6,8,写和替换为字符串(低,中,高)。
look into the cyl and define for cyl 4,6,8, write and substitute with strings (low, medium, high), respectively.
for (i in mtcars$cyl) { if (mtcars$cyl == 4){ print("low")} if (mtcars$cyl == 6) { print ("medium")} if (mtcars$cyl == 8) { print ("high")} }当然不是这样!
Certainly this is not the case!
预期的是这样的:
mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1转换为:
mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 medium 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 medium 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 low 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 medium 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 high 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 medium 225 105 2.76 3.460 20.22 1 0 3 1任何帮助说明是高度赞赏!
推荐答案这个特定的操作将是无循环的。
This particular operation would be possible without loop.
df = mtcars df$cyl[df$cyl == 4] = "low" #Subset the cyl values equal to 4 and assign 'low' #Repeat for other values但是对于运行循环,我会这样去
But for running loop, I would go about like this
df = mtcars for (i in 1:length(df$cyl)) { #Iterate over the length of df$cyl #You could also do "for (i in seq_along(df$cyl)" #Run "seq_along(df$cyl)" and "1:length(df$cyl)" to understand what values are being generated if (df$cyl[i] == 4){ #Index df$cyl by [i]. If the ith value is 4, assign 'low' df$cyl[i] = "low" } if (df$cyl[i] == 6) { df$cyl[i] = "medium" } if (df$cyl[i] == 8) { df$cyl[i] = "high" } }更多推荐
如何为data.fame中的变量执行for循环?
发布评论