[R] sum two columns with same value

Gabor Grothendieck
Sat, 17 Oct 2009 13:38:38 -0000

Here are a few ways:


Here are a few ways:

# 1. using merge

m <- merge(snag_totale, log_totale, all = TRUE)
m[is.na(m)] <- 0
with(m, data.frame(AREA, sum = snag_ha + log_ha))

# 2. Use fact that AREA = 1:7 in log_totale
sum_totale <- log_totale; names(sum_totale)[2] <- "sum"
sum_totale$sum[snag_totale$AREA] <-
log_totale$log_ha[snag_totale$AREA] + snag_totale$snag_ha

# 3. using merge.zoo
# merge.zoo's fill=0 argument makes zero filling easier

library(zoo)

snag_zoo <- read.zoo(snag_totale)
log_zoo <- read.zoo(log_totale)

z <- merge(snag_zoo, log_zoo, all = TRUE, fill = 0)

# produce zoo object:
z$snag_zoo + z$log_zoo

# or produce data frame:
data.frame(AREA = time(z), sum = coredata(z$snag_zoo + z$log_zoo))


On Sat, Oct 17, 2009 at 3:36 AM, Alfredo Alessandrini
<alfreale74 at gmail.com> wrote:
> Hi,
>
> I've two dataframe:
>
>> snag_totale
> ?AREA ? snag_ha
> 1 ? ?2 ?1.628128
> 2 ? ?3 10.274249
> 3 ? ?4 ?2.778503
> 4 ? ?5 73.764307
> 5 ? ?7 12.015985
>> log_totale
> ?AREA ? ?log_ha
> 1 ? ?1 ?22.29846
> 2 ? ?2 ?17.16889
> 3 ? ?3 ?48.80377
> 4 ? ?4 144.18996
> 5 ? ?5 ?70.30962
> 6 ? ?6 ?61.81850
> 7 ? ?7 ?13.24876
>>
>
> How can I obtain a new data.frame, by the sum of value "snag_ha"
+
> "log_ha" in the same "AREA"?
>
> Like this:
>
> ? AREA ? ? ? sum
> 1 ? ?1 ?22.29846
> 2 ? ?2 ?18.79702
> 3 ? ?3 ?59.07801
> 4 ? ?4 146.96847
> 5 ? ?5 144.07392
> 6 ? ?6 ?61.81850
> 7 ? ?7 ?25.26474
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>