Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I have created a dataframe comprising of the following elements:

set.seed(1)

a <- rnorm(1:5,0,1)

b <- rnorm(1:5,0,1)

c <- rnorm(1:5,0,1)

df <- data.frame(a,b,c)

Now I want to have a list that should return a list, first the name of the column and then the data frame. But it doesnt work to return the data frame. 

test <- function(i){

num <- list()

num[1] <- colnames(df)[i]

num[2] <- df

return(num)

}

test(1)

[[1]]

[1] "a"

[[2]]

[1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078

Warning message:

In num[2] <- df :

  number of items to replace is not a multiple of replacement length

1 Answer

0 votes
by (108k points)

What I think is you want to return value of only that respective column.So for doing that you can refer the following code:

test <- function(df, i){

  list(name = colnames(df)[i], value = df[[i]])

}

test(df, 1)

#$name

#[1] "a"

#$value

#[1] -0.63  0.18 -0.84  1.60  0.33

If you are a beginner and want to know more about R programming then do check out the R programming tutorial

Browse Categories

...