Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste values from a vector to column names in R

Tags:

r

i want to paste the values from a vector to the column names of a data frame. Suppose that the file has 4 columns and the tmp2 vector has 4 values. The for loop works perfectly fine(the new colnames is the value of tmp and the value of tmp2 together) but i want to try the same with an apply family function

tmp <- colnames(file)

tmp2 <- c(1,2,3,4)

for(i in 1:length(tmp)){

names(tmp)[i] = paste(tmp[i], tmp2[i])

}

For example something like this

sapply(tmp,function(x,y){

names(x)<-paste(x,y)
},y=tmp2)

Any ideas?

like image 629
Skampak Avatar asked Dec 14 '25 18:12

Skampak


2 Answers

You don't need any loop. The paste is vectorised too. As I have understood OP wants to suffix all column with a sequence number.

Just try:

names(file) <- paste(names(file),1:ncol(file), sep = "")
# A1 B2  C3
# 1  A  1 101
# 2  B  2 102
# 3  C  3 103
# 4  D  4 104
# 5  E  5 105

Data

file <- data.frame(A = "A":"E", B = 1:5, C = 101:105)
file
# A B   C
# 1 A 1 101
# 2 B 2 102
# 3 C 3 103
# 4 D 4 104
# 5 E 5 105
like image 70
MKR Avatar answered Dec 16 '25 10:12

MKR


names(tmp)=mapply(x=tmp,y=tmp2,function(x,y)paste(x,y))

like image 44
Ricardo Fernandes Campos Avatar answered Dec 16 '25 12:12

Ricardo Fernandes Campos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!