How to append column number in front of every element?

五迷三道 提交于 2019-12-08 06:40:52

问题


Here is a simple data:

a <- c( "a" ,"a")
b <- c("b", "b")
df <- data.frame(a, b)

df[] <- paste0(1:2, unlist(df[,1:2]))

   a  b
1 1a 1b
2 2a 2b

The output I am looking for is:

   a  b
1 1a 2b
2 1a 2b

Any efficient way to do this?

This works, but I am sure there is a much better way. Thanks!

df2[] <- paste0(col, unlist(t(df2[,1:2])))
t(df2)

回答1:


Try this:

df[] <- Map(paste0, seq_along(df), df)
df
##    a  b
## 1 1a 2b
## 2 1a 2b


来源:https://stackoverflow.com/questions/52708734/how-to-append-column-number-in-front-of-every-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!