Home > Blockchain >  Using ifelse for a list inside a dataframe
Using ifelse for a list inside a dataframe

Time:08-04

I have a data frame with three columns: value, key, and then list of values. I would like to convert the list of values in column three to the keys they correspond to. For example:

df <- data.frame(value = c(101, 1023, 4284, 4234, 9402),
                  key = c("elephant", "zebra", "hippo", "butterfly", "rhino"),
                  value_lists = c(c(101,4284), c(4234,9402), c(101, 1023), 1023, 9402))



>df$value_lists[1]
[1]  101 4284

I would like to create a new column, key_list, that has the list of keys that correspond to each value_list. So in this example:

>df$value_lists[1]
[1]  101 4284

>df$key_lists[1]
[1] 'elephant', 'hippo'

I thought about trying to make it a data frame instead and join by value, but I was getting a length error. I think I have to use ifelse here with the original df.


It was solved by running this code:

for(i in 1:nrow(df))
{node_sub1$key_lists[i] <- list(df$node[unlist(df$value_lists[i])])} 

CodePudding user response:

This doesn't use an ifelse, but this would provide the result you are looking for. Note that your dataframe didn't seem to work for me, so I had to change it slightly to make the value_lists actually a list.

For df2, where the magic happens, I used a for loop. For each row, it looks for all value_lists items found within df$value. Then use that location on df$key to provide the key for said value. Then make a list of the corresponding keys, and pop it on each row under key_lists.

I'm sure there are ways to do this in a pipe, but I haven't figured it out yet.

   df <- data.frame(value = c(101, 1023, 4284, 4234, 9402),
                   key = c("elephant", "zebra", "hippo", "butterfly", "rhino"), 
                   stringsAsFactors = F)
  df$value_lists = list(c(101,4284), c(4234,9402), c(101, 1023), 1023, 9402)
  
  df2<-df
  for(i in 1:nrow(df)) {
    df2$key_lists[i] <- list(df$key[grep(paste0(unlist(df$value_lists[i]), collapse = "|"), df$value)])
  }

And the result:

> df2
  value       key value_lists        key_lists
1   101  elephant   101, 4284  elephant, hippo
2  1023     zebra  4234, 9402 butterfly, rhino
3  4284     hippo   101, 1023  elephant, zebra
4  4234 butterfly        1023            zebra
5  9402     rhino        9402            rhino
  • Related