1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.