Home > Blockchain >  Append text strings to column cells in R
Append text strings to column cells in R

Time:06-15

Say I have a simple data frame like this in R:

Col1 <- 1:10
Col2 <- 15:6

df <- data.frame(Col1, Col2)

Now I would like to add a text string in a new column that says something about the number in each of those two columns.

df$Eval = "Evaluation:"

When the number in Col1 is >5, I would like to append a text string " Col1) This number is high." to the existing string "Evaluation:". When the number in Col1 is <5, I would like to append " Col1) This number is low." instead. And similarly I would like to append a text string about the number in Col2.

Schematically:

df[df$Col1 >5,]$Eval = " Col1) This number is high."
df[df$Col1 <5,]$Eval = " Col1) This number is low."
df[df$Col2 >9,]$Eval = " Col2) This number is high."
df[df$Col2 <9,]$Eval = " Col2) This number is low."

In the end, the first cell in the column Eval should end up having a text string Evaluation: Col1) This number is low. Col2) This number is high.

How can I achieve this? I've tried to use paste(), but to no avail.

CodePudding user response:

You were almost there. You can indeed use paste as :

Col1 <- 1:10
Col2 <- 15:6

df <- data.frame(Col1, Col2)

# create a new column evaluation
df$Eval = "Evaluation:"

# select the right rows
select <- df$Col1 > 5

# create and allocate your new variable to Eval
df$Eval[select] = paste(df$Eval[select], " Col1) This number is high.")

You can replicate this code for all your specific selection.

CodePudding user response:

Hope this helps:

df <- df %>% mutate( ev_1 = case_when 
                     (Col1 <5 ~ paste("Evaluauation: Col1) This Number is Low."),
                      Col1 >5 ~ ("Evaluauation: Col1) This Number is High.")),
                     ev_2 = case_when
                     (Col2 <9 ~ paste("Col2) This number is Low."),
                       Col2>9 ~ paste("Col2) This number is High.")),
                     Evaluation = paste(ev_1 , ev_2)) %>%
  select(-ev_1, -ev_2)
df  


    Col1 Col2                                                          Evaluation
1     1   15  Evaluauation: Col1) This Number is Low. Col2) This number is High.
2     2   14  Evaluauation: Col1) This Number is Low. Col2) This number is High.
3     3   13  Evaluauation: Col1) This Number is Low. Col2) This number is High.
4     4   12  Evaluauation: Col1) This Number is Low. Col2) This number is High.
5     5   11                                       NA Col2) This number is High.
6     6   10 Evaluauation: Col1) This Number is High. Col2) This number is High.
7     7    9                         Evaluauation: Col1) This Number is High. NA
8     8    8  Evaluauation: Col1) This Number is High. Col2) This number is Low.
9     9    7  Evaluauation: Col1) This Number is High. Col2) This number is Low.
10   10    6  Evaluauation: Col1) This Number is High. Col2) This number is Low
  • Related