简体   繁体   中英

Conditional displaying values in R

I'd like to see which values have a particular entry issue, but I'm not getting things done right. For instance, I need to print on screen values from column "c" but conditional of a given value from "b" say where [b==0]. Finally, I need to add a new string for those whose condition is true.

 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")

I tried this without success:

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


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

Thanks for helping.

The correct syntax is like df[rows, columns] , so you could try:

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

You can accomplish changing values using ifelse :

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

Does this help?

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'
}

There are several ways to subset data in R, like eg:

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

To conditionally add another column (here: 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))
# ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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