Reputation: 1480
I have a dataframe called A. There are six columns in A.
A
Dxa Dxb Dxc Dxd Dxe Dxf
I am wondering how could I instruct to paste A$ prior to each column name. So A ends up being "A$Dxa A$Dxb A$Dxc A$Dxd A$Dxe A$Dxf"
This is to place in the expression below
paste(colnames(A), collapse=" + ")
So it ends up as
A$Dxa + A$Dxb + A$Dxc + A$Dxd + A$Dxe + A$Dxf
Thank you
Upvotes: 0
Views: 3618
Reputation: 44309
It looks like you're trying to add all the columns of a data frame. You can do this with the Reduce
function or the rowSums
function:
# Sample Data
A = data.frame(Dxa=1:3, Dxb=1:3, Dxc=2:4, Dxd=7:5, Dxe=c(0, 0, 100))
A
# Dxa Dxb Dxc Dxd Dxe
# 1 1 1 2 7 0
# 2 2 2 3 6 0
# 3 3 3 4 5 100
# Add Columns
Reduce("+", A)
# [1] 11 13 115
rowSums(A)
# [1] 11 13 115
apply(A, 1, sum)
# [1] 11 13 115
Creating an expression with paste
and then evaluating that expression is not a good way to sum the columns of a data frame.
Upvotes: 0
Reputation: 21497
A<-data.frame(Dxa=numeric(), Dxb=numeric(), Dxc=numeric(),
Dxd=numeric(), Dxe=numeric(), Dxf=numeric() )
paste("A",colnames(A),sep="$", collapse=" + ")
result:
[1] "A$Dxa + A$Dxb + A$Dxc + A$Dxd + A$Dxe + A$Dxf"
EDIT: Alternatively you can use (as Tyler Rinker suggested)
paste0("A$",colnames(A), collapse=" + ")
Upvotes: 1