Home > other >  add a letter to some data points in a column
add a letter to some data points in a column

Time:06-01

I have a numeric column named “date”, which is 4th column in a dataframe, and I want to add a letter “W” at the end of data points in that column, but only across rows 1-150, like “2015W”, “2017W”. The data points in “date” across remaining rows 151-250, should have a letter “E” at the ends, like “2018E”, “2020E”. Any suggestions, guys?

CodePudding user response:

Use paste0() and rep() function as below:

df$date <- paste0(df$date, rep(c("W", "E"), c(150, 100)))

CodePudding user response:

Maybe

paste0(mtcars$mpg,ifelse(row(mtcars[,"mpg",drop=F])<10,"W","E"))

first 10 rows get W, other E.

CodePudding user response:

Assume that your data is:

Data = data.frame(d1=c(1:300), d2=c(1:300), d3=c(1:300), d4=c(2001:2300))

If your choices are not more than two you can use this

Data[1:150,4] = paste0(Data[1:150,4], "W")
Data[151:250,4] = paste0(Data[151:250,4], "E")

and if its more you can use this:

Groups = c(rep("W",150), rep("E", 100), rep("D", 50))
Data[,4] = apply(data.frame(Data[,4], Groups), 1, paste0, collapse="")
  •  Tags:  
  • r
  • Related