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"))
x<-c()
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
df
#> A B G
#> 1 a a a
#> 2 f f f
#> 3 f b f
#> 4 a b b
#> 5 a c c