[R] Replace a column value on condition

Berend Hasselman bhh at xs4all.nl
Mon Mar 23 14:44:16 CET 2015


> On 23-03-2015, at 13:58, Kuma Raj <pollaroid at gmail.com> wrote:
> 
> I want to replace column c3 with values from column c2 whenever values
> of column Id are 2. In stata I could use replace c3 = c2 if id ==2.
> How could I do that in R?
> 


k <- which(df4$id==2)
df4[k,"c3"] <- df4[k,"c2”]

Berend

> Thanks
> 
> 
> Sample data found below:
> 
>> dput(df4)
> structure(list(c2 = c(42L, 42L, 47L, 47L, 55L, 55L, 36L, 36L,
> 61L, 61L), c3 = c(68L, 59L, 68L, 50L, 62L, 50L, 63L, 45L, 65L,
> 45L), id = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)), datalabel = "Written by
> R.              ", time.stamp = "23 Mar 2015 13:54", .Names = c("c2",
> "c3", "id"), formats = c("%9.0g", "%9.0g", "%9.0g"), types = c(253L,
> 253L, 255L), val.labels = c("", "", ""), var.labels = c("", "",
> ""), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9",
> "10"), version = 12L, class = "data.frame")
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list