0

What I am trying to do is to add columns to a data frame but I don't want to write for each column

please consider this example :

for (i in 1:nrow(b){
dataframe$i<-dataframe1[i,2] }

what I am trying to do is to add a column for each loop and assign a name which contain a string and i, is there anyway to do that ?

EDIT :what if the dataframe is a list : please consider this example

I<-list()
for(j in 1:nrow(a)){
I[[j]]<-data.frame(d=1,c=2,d=4.01,stringsAsFactors=FALSE)
for (i in 1:nrow(b)){
I[[j]][[paste0("F",i)]]<-dataframe1[i,2]}}

error for this code : object of type 'closure' is not subsettable

thank you in advance

f.a
  • 101
  • 1
  • 5
  • 14
  • I would suggest you read [this](http://stackoverflow.com/questions/18222286/select-a-data-frame-column-using-and-the-name-of-the-column-in-a-variable) – David Arenburg Nov 17 '14 at 18:47
  • thank you so much for your suggestion @DavidArenburg that was informative but not exactly the answer of my question. – f.a Nov 18 '14 at 03:37

3 Answers3

1
for (i in 1:nrow(b){
dataframe[[paste0("YourString",i)]]<-dataframe1[i,2] }
field210
  • 557
  • 5
  • 11
  • Thank you @field210, that work perfectly well and was what I wanted ,I am having another question regards this : what if the data frame is a list of dataframe, I use this as well but I get this error : object of type 'closure' is not subsettable "I edit the question please see it once more" – f.a Nov 18 '14 at 03:26
1

Here are the replicated columns are the random generated numbers. Please note that I sepcified the length of the matrix created.

my_data <- (cbind(round(runif(10, 0,10),1),rep("B",10)))
my_data2 <- as.data.frame(matrix(NA,ncol=10, nrow=10) )
colnames(my_data2) <- (my_data[,1])  
cbind(my_data,my_data2)
  • thank you for your answer @Jim Button but the previous answer is the answer of my question – f.a Nov 18 '14 at 03:40
0

I find the answer of the EDit part of my question : adding I[[j]]<-data.frame()

I<-list()
for(j in 1:nrow(a)){
I[[j]]<-data.frame()
I[[j]]<-data.frame(d=1,c=2,d=4.01,stringsAsFactors=FALSE)
for (i in 1:nrow(b)){
I[[j]][[paste0("F",i)]]<-dataframe1[i,2]}}
f.a
  • 101
  • 1
  • 5
  • 14