0
votes

My problem statement is I have a list of dataframes as df1,df2,df3.Data is like

df1

a,b,c,d
1,2,3,4

1,2,3,4

df2

a,b,c,d

1,2,3,4

1,2,3,4

Now, for these two dataframe I should create a new dataframe taking aggregated column of those two dataframes ,for that I am using below code

for(i in 1:2){
 assign(paste(final_val,i,sep=''),sum(assign(paste(df,i,sep='')))$d*100)}

I am getting the error:

Error in assign(paste(hvp_route_dsct_clust, i, sep = "")) : argument "value" is missing, with no default

My output should look like

final_val1 <- 800
final_val2 <- 800

And for those values final_val1,final_val2 I should be creating dataframe dynamicaly

Can anybody please help me on this

1
It is unclear how the final values relate to your dataframes. Could you elaborate on "taking aggregated column of those two dataframes" please? The error in your question is because you have only one argument to assign instead of two.mathematical.coffee
Probably my approach of using the assign function might be wrong the problem statement is "df1 df2 dataframes column d should sum , multiply with 100 and assign to two new variables so those are the values of final_val1 and final_val2 and this final_val1 final_val2 should be formed dynamically as an dataframe".Naveen Srikanth

1 Answers

1
votes

If we need to use assign, get the object names from the global environment with ls by specifying the pattern 'df' followed by one or more numbers (\\d+), create another vector of 'final_val's ('nm1'), loop through the sequence of 'nm1', assign each of the element in 'nm2' to the value we got from extracting the column 'd' of each 'df's multiplied by 100 and taking its sum.

nm1 <- ls(pattern = "df\\d+")
nm2 <- paste0("final_val", seq_along(nm1))
for(i in seq_along(nm1)){
   assign(nm2[i], sum(get(nm1[i])$d*100))
}
final_val1
#[1] 800
final_val2
#[1] 800

Otherwise, we place the datasets in a list, extract the 'd' column, multiply with 100 and do the column sums

unname(colSums(sapply(mget(nm1), `[[`, 'd') * 100))
#800 800 

data

df1 <- structure(list(a = c(1L, 1L), b = c(2L, 2L), c = c(3L, 3L), d = c(4L, 
4L)), .Names = c("a", "b", "c", "d"), class = "data.frame", row.names = c(NA, 
-2L))

df2 <- structure(list(a = c(1L, 1L), b = c(2L, 2L), c = c(3L, 3L), d = c(4L, 
4L)), .Names = c("a", "b", "c", "d"), class = "data.frame", row.names = c(NA, 
-2L))