Home > Mobile >  Is there a way to edit a list in a dataframe
Is there a way to edit a list in a dataframe

Time:12-04

I have added a list to the dataframe as shown below

new_df <- structure(list(ID = list(ID = "21", ID = "4"), 
               MET = structure(list(c("A", "B"), c("C", "D")), .Names = c("","")), 
               REGN = structure(list(c("ALL", "US"), "ALL"), .Names = c("", "")), 
               YEAR = list(YEAR = "2020", YEAR = "2020"), 
               WEEK = list(WEEK = c("12", "13", "14"), WEEK = "16"), 
               ANN = list(ANN = "Seller",ANN = "Rise")), row.names = 1:2, class = "data.frame")


new_df
  ID  MET    REGN YEAR       WEEK    ANN
1 21 A, B ALL, US 2020 12, 13, 14 Seller
2  4 C, D     ALL 2020         16   Rise

Suppose if i want to edit the rows here. For example, i need to edit 1 row and REGN column so

new_df[1,"REGN"] <- list(c(New "ALL", "New US"))
Warning message:
In `[<-.data.frame`(`*tmp*`, 1, "REGN", value = list(c("ALL", "USNew" :
  replacement element 1 has 2 rows to replace 1 rows

Expected output

new_df
  ID  MET            REGN    YEAR       WEEK    ANN
1 21 A, B New ALL, New US    2020 12, 13, 14 Seller
2  4 C, D              ALL   2020         16   Rise

CodePudding user response:

You can use $ to access the column, then select the row with [].

new_df$REGN[1] <- list(c("New ALL", "New US"))

Output

  ID  MET            REGN YEAR       WEEK    ANN
1 21 A, B New ALL, New US 2020 12, 13, 14 Seller
2  4 C, D             ALL 2020         16   Rise
  •  Tags:  
  • r
  • Related