Reputation: 2605
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
Upvotes: 4
Views: 10276
Reputation: 1044
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
Upvotes: 0
Reputation: 46
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)
Upvotes: 3