简体   繁体   English

有类似x的方法吗? y:R中的z?

[英]Is there a similar way like x ? y : z in R?

With

df <- data.frame(v1=c(1:5), v2=c(9,32,6,17,11))

I need to add a new column v3 with value 1 or 0 based on whether values in v2 are larger than 10 or not so that: 我需要根据v2中的值是否大于10添加一个值为1或0的新列v3,以便:

df
  v1 v2 v3
1  1  9  0
2  2 32  1
3  3  6  0
4  4 17  1
5  5 11  1

Is there such thing like x ? 有像x这样的东西吗? y : z in R? y:R中的z? If not, what's a good way to solve the above? 如果没有,什么是解决上述问题的好方法? Thanks! 谢谢!

ifelse(..) comes closest: ifelse(..)最接近:

R> df <- data.frame(v1=c(1:5), v2=c(9,32,6,17,11))
R> df$v3 <- ifelse(df$v2 > 10, 1, 0)
R> df
  v1 v2 v3
1  1  9  0
2  2 32  1
3  3  6  0
4  4 17  1
5  5 11  1
R> 

I don't know whether ifelse is faster, but this is easier to read: 我不知道ifelse是否更快,但这更容易阅读:

> d <- data.frame(v1=c(1:5), v2=c(9,32,6,17,11))
> d$v3 <- as.numeric(d$v2 > 10)
> d
  v1 v2 v3
1  1  9  0
2  2 32  1
3  3  6  0
4  4 17  1
5  5 11  1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以整洁的形式将诸如z &lt;-x ^ 2 / y ^ 2之类的R方程插入Markdown - Insert R equation like `z<-x^2/y^2` into Markdown in a neat form 有没有办法让X上的最大值(从X,Y,Z中确定)决定R中的V值? - Is there a way to let biggest value on X (out of X, Y, Z) decide value on V in R? R 中从输入向量 x,y 和用户定义的函数 f(x,y) 生成输出矩阵 Z 的简单方法 - Simple way in R to generate an output matrix Z from input vectors x,y and a user defined function f(x,y) 给定值 (z) 的 R plot 等倾线,其中 x*y=z - R plot isoclines for a given value (z), where x*y=z 在R中以“V,W,X,Y和Z”样式输出列表的简单方法 - Simple way to output list in the style “V, W, X, Y, and Z” in R 将c(“x”,“y”,“z”)之类的矢量转换为函数(x,y,z){} - Convert vector like c(“x”,“y”,“z”) to function(x , y, z){} 将具有x,y和z的列表转换为数据帧,其中x,y和z在R中的长度不相等 - Convert a list with x, y and z to data frame where x, y and z are of unequal lengths in R 有没有办法根据 x、y、z 值制作强度的 2D 圆形密度 plot; 看起来像 stat_density2d plot? - Is there a way to make a 2D circular density plot of intensity from x, y, z values; that looks like the stat_density2d plot? 在R?中绘制以y为点,x和z为向量的3d。 - Plot 3d with y as point, x and z as vectors in R? R 中的 3D 曲面图,给定 x,y,z 坐标 - 3D surface plot in R, given x,y,z coordinates
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM