I am trying to write some code in R for a large process but I keep on getting this error:
Example <- data.frame(Col1 = c(1, 2, 3, 4, 5),
COl2 = c("A", "B", "C", "D", "E"))
Example[Example$Col1 > 3,]$Col1 <- 3 #works fine, 2 rows were selected
Example[Example$Col1 < -5,]$Col1 <- 0 #gets an error, 0 rows were selected
Error in `$<-.data.frame`(`*tmp*`, Col1, value = 0) :
replacement has 1 row, data has 0
I know that what causes the error is that zero rows where selected, and thus the replacement cannot be made. But to my process to work, I wouldn't mind if the line was just skipped.
I know that I can avoid it with an if:
if(sum(Example$Col1 < -5) > 0){
Example[Example$Col1 < -5,]$Col1 <- 0
}
But I was wondering if there is an easier (or cleaner) way to do it. Any hints?
This error usually occurs for one of two reasons: Reason 1: You are attempting to reference an object you have not created. Reason 2: You are running a chunk of code where the object has not been defined in that chunk.
One simple approach to creating an empty DataFrame in the R programming language is by using data. frame() method without any params. This creates an R DataFrame without rows and columns (0 rows and 0 columns).
To get number of rows in R Data Frame, call the nrow() function and pass the data frame as argument to this function. nrow() is a function in R base package.
To add row to R Data Frame, append the list or vector representing the row, to the end of the data frame. nrow(df) returns the number of rows in data frame. nrow(df) + 1 means the next row after the end of data frame. Assign the new row to this row position in the data frame.
Write like this instead:
Example$Col1[Example$Col1 > 3] <- 3
Example$Col1[Example$Col1 < -5] <- 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With