Ketty
Ketty

Reputation: 851

How to append column number in front of every element?

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)

Upvotes: 1

Views: 49

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269824

Try this:

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

Upvotes: 3

Related Questions