Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to batch calculate the average values of different factors and levels in R language summary statistics

Shulou Source: shulou.com Published: 2022-06-01 03:01:38 10月04日 Update

This article will explain in detail how to batch calculate the averages of different factors and different levels in R language summary statistics. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

In practice, we need to calculate the average value of the data. Here I compare the methods of aggregate and data.table. The tests mainly include:

1, calculate the average of the data yield

2. Calculate the average value of different levels of N

3. Calculate the average values of different levels of N and P

1. Conventional method aggregate

Code:

Data (npk)

Head (npk)

Aggregate (yield~N,data=npk,FUN = mean)

Aggregate (yield~N+P,data=npk,FUN = mean)

Result

> aggregate (yield~N,data=npk,FUN = mean)

N yield

1 0 52.06667

2 1 57.68333

> aggregate (yield~N+P,data=npk,FUN = mean)

N P yield

1 0 0 51.71667

21 0 59.21667

3 0 1 52.41667

4 1 1 56.15000

two。 Use the data.table method

Code:

Data (npk)

Head (npk)

Library (data.table)

SetDT (npk)

# single variable

Npk [, mean (yield), by=N]

# two variables

Npk [, mean (yield), by=c ("N", "P")]

# another way to write two variables

Npk [, mean (yield), by=list (NMagol P)]

Npk [, mean (yield), by=. (NMagol P)]

Results:

> # single variable

> npk [, mean (yield), by=N]

N V1

1: 0 52.06667

2: 1 57.68333

>

> # two variables

> npk [, mean (yield), by=c ("N", "P")]

N P V1

1: 0 1 52.41667

2: 1 1 56.15000

3: 0 0 51.71667

4: 1 0 59.21667

>

>

> # another way to write two variables

> npk [, mean (yield), by=list (NMague P)]

N P V1

1: 0 1 52.41667

2: 1 1 56.15000

3: 0 0 51.71667

4: 1 0 59.21667

> npk [, mean (yield), by=. (NMague P)]

N P V1

1: 0 1 52.41667

2: 1 1 56.15000

3: 0 0 51.71667

4: 10 59.21667 this is the end of the article on "how to batch calculate the average of different factors and different levels in R language Summary Statistics". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Different average variable level two method article factor language statistics code writing single data more result good practical content actual Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Microsoft OPPO Reno macOS Xiaomi