I'm about to throw R out of the window. R is lovely, but sometimes a little problem takes hours to get solved.
Got this df:
Product <- c("Basket", "Basket", "Basket", "Apple", "Apple", "Apple", "Corn", "Corn", "Corn", "Basket")
Place <- c("America", "Europe", "Africa", "America", "Europe", "Africa", "America", "Europe", "Africa", "America")
Detail <- c("Income", "Income", "Outcome", "Outcome", "Income", "Outcome", "Outcome", "Income", "Income", "Outcome")
Valuex <- c(1500, 2000, 2000, 4000, 5000, 700, 4000, 2000, 7000, 450)
df_test <- data.frame(Product, Place, Detail, Valuex, stringsAsFactors = FALSE)
Then, I create another data.frame
by doing this:
test <- df_test[1,]
At last, I use cbind
like this:
test[1,1:4] <- cbind(df_test[1,1:2], "Prueba", df_test[1, 4])
And when I look into the data frame test
I find this:
Product Place Detail Valuex
1 Basket America 1 1500
Instead of saving "Prueba", saves 1.
I've tried as.character("Prueba")
, c("Prueba")
, paste("Prueba")
, but it still puts 1.
Could anyone help me?
The reason you keep seeing 1
in place of Preuba
, is that the value is being converted to a factor, and you are seeing the level value. You may avoid this by assigning the first row of test
to a cbind
call which has stringsAsFactors
set to false, e.g.
test <- df_test[1,]
df <- cbind(df_test[1,1:2], "Prueba", df_test[1, 4], stringsAsFactors=FALSE)
test[1,] <- df
test
Product Place Detail Valuex
1 Basket America Prueba 1500
However, a possibly better workaround to your problem is to just assign a vector to the first row of the test
data frame:
test[1,] <- c(df_test[1,1:2], "Prueba", df_test[1, 4])