简体   繁体   中英

add a letter to some data points in a column

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?

使用paste0()rep()函数如下:

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

Maybe

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

first 10 rows get W, other E.

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="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM