如何为data.fame中的变量执行for循环?

编程入门 行业动态 更新时间:2024-10-26 14:33:07
本文介绍了如何为data.fame中的变量执行for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在 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循环?

本文发布于:2023-11-29 19:17:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647380.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   何为   data   fame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!