简体   繁体   中英

Insert a vector into a specific cell of data frame in R

I have a small situation in R.

I have a dataframe as below:

                 age
numCategories      9
signFeatures      NA
nullDeviance      NA
residualDeviance  NA
aic               NA

I want to insert a vector as c(1,2,3) in a particular cell of the data frame.

For example my data frame after replacement should look somethinglike:

                  age
numCategories      9
signFeatures      c(1,2,3)
nullDeviance      NA
residualDeviance  NA
aic               NA

I tried doing the below:

df['signFeatures', 'age'] <- c(1,2,3) &
df['signFeatures', 'age'] <- Vectorize(c(1,2,3))

Both the time it gives me the same error:

Error in `[<-.data.frame`(`*tmp*`, "signFeatures", "age", value = c(1,  : 

replacement has 3 rows, data has 1

I understand the problem, but cant find a way to solve it.

Any help would be appreciated

Like Andrew mentioned above, each column of a data frame has to have to same class, so you can record, instead, a transposed version of your desired table above:

data <- data.frame(numCategories = 9)
data$signFeatures <- list(c(1,2,3))
data$nullDeviance <- rnorm(1)
data$residualDeviance <- rnorm(1)
data$aic <- rnorm(1)

Well I do not know if it is possible with data frames, but is possible with Tibbles .

Here is an approach using mutate() and case_when() :

library(dplyr)
library(tidyr)

df = tibble(Type = c("numCategories", "signFeatures", "nullDeviance", "residualDevian","aic"),
           age = NA
            ) %>% mutate(age =  case_when(Type == "numCategories" ~ list(9),
                                          Type == "signFeatures" ~ list(c(1,2,3))
                                          )
                         )

You can print the results individually as follow:

df[2,"age"][[1]] %>% unlist()
## [1] 1 2 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM