简体   繁体   中英

R, generating dataframe row from factor values

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.

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

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