babesz - 1 year ago 140
R Question

# How to use ifelse and paste functions

I am learning the use of the ifelse function from Zuur et al (2009) A Beginners guide to R. In one exercise, there is a data frame called Owls which contains data about about 27 nests and two night of observations.

``````structure(list(Nest = structure(c(1L, 1L, 1L, 1L), .Label = "AutavauxTV", class = "factor"),
FoodTreatment = structure(c(1L, 2L, 1L, 1L), .Label = c("Deprived",
"Satiated"), class = "factor"), SexParent = structure(c(1L,
1L, 1L, 1L), .Label = "Male", class = "factor"), ArrivalTime = c(22.25,
22.38, 22.53, 22.56), SiblingNegotiation = c(4L, 0L, 2L,
2L), BroodSize = c(5L, 5L, 5L, 5L), NegPerChick = c(0.8,
0, 0.4, 0.4)), .Names = c("Nest", "FoodTreatment", "SexParent",
"ArrivalTime", "SiblingNegotiation", "BroodSize", "NegPerChick"
), row.names = c(NA, 4L), class = "data.frame")
``````

The two nights differed as to the feeding regime (satiated or deprived) and are indicated in the Foodregime variable. The task is to use ifelse and past functions that make a new categorical variable that defines observations from a single night at a particular nest.

In the solutions the following code is suggested:

``````Owls <- read.table(file = "Owls.txt", header = TRUE, dec = ".")
ifelse(Owls\$FoodTreatment == "Satiated", Owls\$NestNight <- paste(Owls\$Nest, "1",sep = "_"), Owls\$NestNight <- paste(Owls\$Nest, "2",sep = "_"))
``````

and apperently it creates a new variable with values the endings of which vary ("-1" or "-2")

however when I call the original dataframe, all "-1" endings in the NestNight varibale disappear and are turned to "-2."

Why does thsi happen? Did the authors missed something from the code or it's me who is not getting it?

Many thanks

EDIT: Sorry, I wanted to give a reproducible example by copying my data using dput but it did not work. If you can let me know how I can correct it so that it appears properly, I'd be greatful too!

Solution

If you do the assignment outside the `ifelse` structure, it works:

``````Owls\$NestNight <- ifelse(Owls\$FoodTreatment == "Satiated",
paste(Owls\$Nest, "1",sep = ""),
paste(Owls\$Nest, "2",sep = ""))
``````

Explanation

What happens in your case is simply if you would execute the following two lines:

``````Owls\$NestNight <- paste(Owls\$Nest, "1",sep = "")
Owls\$NestNight <- paste(Owls\$Nest, "2",sep = "")
``````

You first assign `paste(Owls\$Nest, "1",sep = "")` to `Owls\$NestNight` and then you reassign `paste(Owls\$Nest, "2",sep = "")` to it. The `ifelse` is not affected by this, but you don't assign it's result to any variable. Maybe it is more clear if you test this simple code:

``````c(a <- 1:5, a <- 6:10) #c is your ifelse, a is your Owls\$NestNight
a #[1]  6  7  8  9 10
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download