R If else - from a df add a column with values from the other columns

Hi community

I would appreciate if you could help me, I am trying to add a column with the info from diferents columns.
For the example, I requered add thecolumn G with the specific text from the df. If the column A is == f then print in G "f" else Print for each row the column info in column B.

df<- data.frame("A" = c("a","f","f","a","a"),"B" = c("a","f","f","a","a"))


for (i in 1:length(df$A)) {
  if(df$A[i] == "f" ){
    DF$G[i] = "f"
  } else{
    df$G[i] <- df$B

Your example is a little odd because A and B are the same so I changed the initial example a little bit. This code is how I would do it in Base R. R is cool because it's vectorized and you often don't have to use loops.

df<- data.frame("A" = c("a","f","f","a","a"),"B" = c("a","f","b","b","c"))

df$G <- ifelse(df$A=="f", "f", df$B) #test, yes, no

#>   A B G
#> 1 a a a
#> 2 f f f
#> 3 f b f
#> 4 a b b
#> 5 a c c

Created on 2021-12-17 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.