Home > Back-end >  Multiline text in R dataframe
Multiline text in R dataframe

Time:09-06

I'm trying to include a multiline text in a dataframe cell, however R keeps reading the \n as a next row, resulting in row mismatches. If i change the 'code' input to a simple string, the code works fine.

Defined dataframe:

  df <- data.frame(
    "Id" = character(),
    "Name" = character(),
    "Code" = character()
  )

Adding new row:

NewRow <- data.frame(
  "Id" = Id,              # Simple string
  "Name" = Name,          # Simple string
  "Code" = Code           # Complex multiline string containing '#' and '\n' (10  lines)
)
df <- rbind(df, NewRow)

Received error: Error in data.frame: arguments imply differing number of rows: 1, 0

Does anyone know how to get around this problem?

Many thanks in advance!

CodePudding user response:

Maybe what you can try is to clean up the Code variable a bit, before adding it to the dataframe. In this sense, you can remove \n and # from the Code variable, and then add it inside the dataframe. For this you can use stringr and dplyr, to update the Code variable:

### Using the replace option: 
    Code <- Code %>% 
             str_replace_all("\\\n", "") %>% 
             str_replace_all("#", "")

### Using the remove option: 
    Code <- Code %>% 
             str_remove_all("\\\n") %>% 
             str_remove_all("#")
         
  • Related