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

2
  • I would suggest you read this Commented Nov 17, 2014 at 18:47
  • thank you so much for your suggestion @DavidArenburg that was informative but not exactly the answer of my question. Commented Nov 18, 2014 at 3:37

3 Answers 3

1
for (i in 1:nrow(b){
dataframe[[paste0("YourString",i)]]<-dataframe1[i,2] }
Sign up to request clarification or add additional context in comments.

1 Comment

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"
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)

1 Comment

thank you for your answer @Jim Button but the previous answer is the answer of my question
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]}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.