繁体   English   中英

R中的条件显示值

[英]Conditional displaying values in R

我想看看哪些值存在特定的输入问题,但是我做得不好。 例如,我需要在屏幕上打印列“ c”中的值,但要以“ b”中给定值的条件为条件,其中[b == 0]。 最后,我需要为条件为真的用户添加一个新字符串。

 df<- structure(list(a = c(11.77, 10.9, 10.32, 10.96, 9.906, 10.7, 
 11.43, 11.41, 10.48512, 11.19), b = c(2, 3, 2, 0, 0, 0, 1, 2, 
 4, 0), c = c("q", "c", "v", "f", "", "e", "e", "v", "a", "c")), .Names = c("a", 
 "b", "c"), row.names = c(NA, -10L), class = "data.frame")

我尝试了一下但没有成功:

if(df[b]==0){
print(df$c)
}


if((df[b]==0)&(df[c]=="v")){
df[c] <-paste("2")
}

感谢您的帮助。

正确的语法类似于df[rows, columns] ,因此您可以尝试:

df[df$b==0, "c"]

您可以使用ifelse完成更改值:

df$c <- ifelse(df$b==0 & df$c=="v", paste(df$c, 2, sep=""), df$c)

这有帮助吗?

rows <- which(df$b==0)
if (length(rows)>0) {
  print(df$c[rows])
  df$c[rows] <- paste(df$c[rows],'2')
  ## maybe you wanted to have:
  # df$c[rows] <- '2'
}

有几种方法可以在R中对数据进行子集化,例如:

df$c[df$b == 0]
df[df$b == 0, "c"]
subset(df, b == 0, c)
with(df, c[b == 0])
# ...

要有条件地添加另一列(此处为TRUE / FALSE):

df$e <- FALSE; df$e[df$b == 0] <- TRUE
df <- transform(df, c = ifelse(b == 0, TRUE, FALSE))
df <- within(df, e <- ifelse(b == 0, TRUE, FALSE))
# ...

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM