Using an if statement in apply in R for every value in a data frame

Related searches

I have a data frame that I created using the read_excel function and then duplicated it. I'm going to explain it as if I was using Excel, because it's so easy to do this in Excel. I want to check if each cell in each row within columns 3 to 11 have a zero, and if so, put a zero in columns 12 to 20. If not, keep the original value.

Data2 <- Data1

Data2[,12:20] <- apply(Data1[,3:11],1:2,function(x) {if(x==0) {0})

This is the error message I get:

Warning message: In [<-.data.frame(*tmp*, , 12:20, value = list(0, 0, 0, 0, 0, : provided 450 variables to replace 9 variables

Example:

Data1 <- matrix(data=c(0,1,1,0,3,4,5,6,2,3,0,5,6,5,6,2,6,2,3,4,5,6,5,6),nrow=6,ncol=4)
Data2 <- Data1
Data2[,3:4] <- apply(Data1[,1:2],1:2,function(x) if(x==0) {0})
Data2 <- matrix(Data2,nrow=6,ncol=4)

The result should look like this:

     [,1] [,2] [,3] [,4]
[1,]    0    5    0    3
[2,]    1    6    5    4
[3,]    1    2    6    5
[4,]    0    3    0    6
[5,]    3    0    6    0
[6,]    4    5    2    6

where any zero in columns 1 and 2 become zeros in the appropriate spot in columns 3 and 4.

Instead, I get this:

     [,1] [,2] [,3] [,4]
[1,] 0    5    0    NULL
[2,] 1    6    NULL NULL
[3,] 1    2    NULL NULL
[4,] 0    3    0    NULL
[5,] 3    0    NULL 0   
[6,] 4    5    NULL NULL

Also, I'm still getting the same error message from the original data that had 50+ row and 20 columns shown at the beginning.

There's probably a more elegant solution, but this works:

for (j in seq(nrow(Data1))) {

  for (i in seq(2)) {

    if (Data1[j,i] == 0) {

      Data1[j,i + 2] <- 0

    }
  }
}

Result:

> Data1
     [,1] [,2] [,3] [,4]
[1,]    0    5    0    3
[2,]    1    6    5    4
[3,]    1    2    6    5
[4,]    0    3    0    6
[5,]    3    0    6    0
[6,]    4    5    2    6

Obviously, you'll want to tweak the 2 in i in seq(2) and Data[j,i + 2] <- 0 to fit the correct number of columns over which you're iterating this.

Loops and Functions in R, Make decisions with if and else statements; Use a for loop to repeat For example, we can do something to every row of our dataframe. Using the names above, each iteration of variable takes the value of one of the elements of vector . Write a function that will calculate the volume of the animals skulls and apply it to� You can use with() function to avoid mentioning data frame each time. It makes writing R code faster. It makes writing R code faster. mydata$y = with(mydata, ifelse(x3 %in% c("A","B") , x1*2, ifelse(x3 %in% c("C","D"), x1*3, x1*4)))

Here is an alternative solution:

First, create a logical matrix representing which elements are 0 in the columns of interest.

mat <- Data1[,1:2] == 0
mat

      [,1]  [,2]
[1,]  TRUE FALSE
[2,] FALSE FALSE
[3,] FALSE FALSE
[4,]  TRUE FALSE
[5,] FALSE  TRUE
[6,] FALSE FALSE

Then, select the elements for the target columns where the logical matrix has a TRUE value and set those to 0:

Data2[,3:4][mat==TRUE] <- 0
Data2

     [,1] [,2] [,3] [,4]
[1,]    0    5    0    3
[2,]    1    6    5    4
[3,]    1    2    6    5
[4,]    0    3    0    6
[5,]    3    0    6    0
[6,]    4    5    2    6

R tutorial on the Apply family of functions, In this tutorial we show the use of apply in R, its variants, and a few of its A note for the following: in most cases, R can return a value even if the You want to apply a given function to every element of a list and Note that if you want to see the number of rows and columns that the dataframe contains,� An if statement can deal only with a single value, but the expression hours > 100 returns two values, as shown by the following code: > c (25, 110) > 100 FALSE TRUE Choose based on a logical vector in R The solution you’re looking for is the ifelse () function, which is a vectorized way of choosing values from two vectors.

With R, you always want to work with vectors, ifelse is a great way to do an if statement on a vector. It is generally slow to use for loops in R and applying a function to each element in a matrix I believe is reserved for a different apply function, but I do not know which. Applies are sensitive to their return types also, So sense you are trying to append a data frame, using the standard apply and working on the columns (as most data frames in R are expected to be handled), it makes it easy to add additional columns.

Data2[,12:20] <- apply(Data1[,3:11], 2, function(x){ifelse(x==0,0,x)})

Basics of R Programming, To convert htwtmatrix to a data frame, we use the command: In R, one can write a conditional statement as follows: Whereas & (and) and | (or) apply element- wise to vectors, && and || apply to vectors of length one, and Sometimes deleting all cases with missing values is useful, and sometimes it is a horrible idea… data<-c(0,1,2,3,4,2,3,1,4,3,2,4,0,1,2,0,2,1,2,0,4) frame<-as.data.frame(data) I now want to create a new variable within this data frame. If the column "data" reports a number of 2 or more, I want it to have "2" in that row, and if there is a 1 or 0 (e.g. the first two observations), I want the new variable to have a "1" for that observation.

R : If Else and Nested If Else, In this tutorial, we will see various ways to apply conditional statements (If..Else nested IF) in R. In R, there are a lot of powerful packages for data manipulation. In the later part of this IF ELSE function. This data frame would be used further in examples. ifelse(condition, value if condition is true, value if condition is false )� In R, you can use the apply() function to apply a function over every row or column of a matrix or data frame. This presents some very handy opportunities. Count in R using the apply function Imagine you counted the birds in your backyard on three different days and stored the counts in a matrix […]

16 Loop Functions, When you pass a function to lapply() , lapply() takes elements of the list and passes The lapply() function and its friends make heavy use of anonymous functions. We can split the airquality data frame by the Month variable so that we have� The apply() collection is bundled with r essential package if you install R with Anaconda. The apply() function can be feed with many functions to perform redundant application on a collection of object (data frame, list, vector, etc.). The purpose of apply() is primarily to avoid explicit uses of loop constructs.

Dear R experts, I have again a problem. Let I have a data frame like below: x y ----- A A A B B B A B where x and y are the column names. I want to create a new column z where it is elements will be like that, if at each row has there at least one 'B', then z will have value of B, if not then Z will have missing value(NA) for the corresponding row.

Comments
  • Can you add a small example of your data
  • Sure, I've added an example in the text.
  • An extra { before if is causing the second error.
  • Can you provide what Data2 should end up with in the end?
  • This is exactly what I was looking for. Thank you!
  • The problem with this is I don't want x to be put it its place. I want the original data to remain in columns 12:20. I believe this is replacing all of the data in 12:20 with the data in 3:11.