Home > Net >  Creation of a new logical column inside a for loop if named as the value in the column in R
Creation of a new logical column inside a for loop if named as the value in the column in R

Time:07-15

Thanks in advance for your kind help. This is my dataframe:

df <- data.frame('a'=c(1,2,3,4,5), 'b'=c("A",NA,"B","C","A"))
df

And I want to create a new column based on if the value of dataframe$b is present/or absent (TRUE/FALSE). I'm using grepl for this but I'm not sure how to dinamically create the new column.

I'm creating a vector with the unique values of df$b

list <- as.vector(unique(df$b))

And want to iterate with a for in df$b, in order to get a dataframe like this:

         a     b      A     B     C
    1    1     A   TRUE  FALSE FALSE
    2    2     NA  FALSE FALSE FALSE
    3    3     B   FALSE  TRUE FALSE
    4    4     A   FALSE FALSE  TRUE
    5    5     A   TRUE  FALSE FALSE

But I'm not sure how to generate the new column inside the for loop. I'm trying to do something like this:

for (i in list) {
logical <- grepl(df$b, i)
df$i <- logical

But it generates an error. Any help will be appreciated

CodePudding user response:

This may need table

df <- cbind(df,  as.data.frame.matrix(table(df) > 0))

-output

df
 a    b     A     B     C
1 1    A  TRUE FALSE FALSE
2 2 <NA> FALSE FALSE FALSE
3 3    B FALSE  TRUE FALSE
4 4    C FALSE FALSE  TRUE
5 5    A  TRUE FALSE FALSE

CodePudding user response:

You can use this for loop

list <- as.vector(unique(na.omit(df$b)))

for(i in 1:length(list)){
    `[[`(df , list[i]) <- ifelse(!is.na(df$b),
     list[i] == df$b , FALSE)
}
  • output
  a    b     A     B     C
1 1    A  TRUE FALSE FALSE
2 2 <NA> FALSE FALSE FALSE
3 3    B FALSE  TRUE FALSE
4 4    C FALSE FALSE  TRUE
5 5    A  TRUE FALSE FALSE
  • Related