0
votes

I have a dataframe df with 50 columns, and I would like to generate vector objects for each column name, with the length of the dataframe rows.

My code throws out an error:

for i in ((1:ncol(df)) {
  colnames(df)[i] <- vector(mode = "list", length = nrow(df))
  return (colnames(df)[i])
}

The error:

for i in ((1:ncol(df)) { Error: unexpected symbol in "for i" colnames(df)[i] <- vector(mode = "list", length = nrow(df)) Error in colnames(df)[i] <- vector(mode = "list", length = nrow(df)) :
object 'i' not found return (colnames(df)[i]) Error: object 'i' not found } Error: unexpected '}' in "}"

P.S. Some of the columns in my dataframe are nested lists, just in case this affects the operation.

3
Could you please show an example of your df?, Is not clear what you want to achieve? - S Rivero
What should the output look like? - Alex P

3 Answers

1
votes

for(i in (1:ncol(df)))<----- parenthesis in wrong place

0
votes
for (i in 1:ncol(df)) {
  colnames(df)[i] <- vector(mode = "list", length = nrow(df))
  return (colnames(df)[i])
}

I'm gonna guess that you want the number of entries in each column. Normally, in a dataframe, every column has the same number of rows. But you have list columns, so you want to calculate how long they are, unnested?

lapply(df, function(x) length(c(x, recursive=TRUE) ) )
0
votes

Making the same assumption than @Alex P and saying than his lapply solution is always more efficient than a for loop in R. If you still want to use a for loop, this is an option:

df <- data.frame(a=1:3)
df$b <- list(1:1, 1:2, 1:3)

l<-list(NULL)
for (i in colnames(df)){
    p <- length(unlist(df[,i]))
    l[[i]] = p
}