Reputation: 1986
I have an R data frame with factor columns.
dataframe <- read.csv("import.csv")
dataframe$col1 = as.factor(dataframe$col1)
dataframe$col2 = as.factor(dataframe$col2)
...
How can I generate a new row from labels?
newRow = dataframe[1,] #template
newRow[1] = ?
newRow[2] = ?
Lets say col1
includes "TestValue"
. I would like to set newRow[1]
value to "TestValue"
as if it was selected from my dataframe
. How can I do that?
I know I can get factor index like so:
match(c("TestValue"),levels(dataframe$col1))
[1] 3
But whenever I assign anything to newRow[1]
, I seem to change its type.
Thanks in advance.
Upvotes: 1
Views: 57
Reputation: 37879
You could assign a factor
to newRow[1]
and maintain the levels too.
In your case:
newRow[1] <- factor('TestValue', levels = levels(df$col1))
As an example:
df <- data.frame(a = letters, b = letters)
new <- df[1, ]
new[1] <- factor('b', levels = levels(df[[1]]))
Output:
> str(new)
'data.frame': 1 obs. of 2 variables:
$ a: Factor w/ 26 levels "a","b","c","d",..: 2
$ b: Factor w/ 26 levels "a","b","c","d",..: 1
column a is still a factor with all the levels
Upvotes: 2