Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R dataframe error - Replacement has 1 row, data has 0

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?

like image 350
RMolero Avatar asked Oct 29 '17 14:10

RMolero


People also ask

Why is object not found in R?

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.

How do I create an empty Dataframe in R?

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).

How do I number rows in a Dataframe in R?

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.

How do I manually add a row to a Dataframe in R?

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.


1 Answers

Write like this instead:

Example$Col1[Example$Col1 > 3] <- 3
Example$Col1[Example$Col1 < -5] <- 0
like image 115
janos Avatar answered Oct 01 '22 22:10

janos