[英]How to subtract one column from multiple columns in a dataframe in R using dplyr
我正在使用 gapminder 數據從其他國家減去 1 個國家 gdpPercapita 的值。
我已經提到了關於同一主題的鏈接,但仍然遇到問題。 從 R 中的許多列中減去數據框中的一列)
問題當我從所有其他國家/地區減去一列(例如印度)時,作為回報,我將印度作為 0 值(這是正確的),但它沒有從其他列(例如越南)中減去印度。
減去前比較印度和越南的樞軸數據
gapminder %>%
select(country, year, gdpPercap) %>%
pivot_wider(names_from = country, values_from = gdpPercap) %>%
arrange(year) %>%
select(year,India,Vietnam)
year India Vietnam
<int> <dbl> <dbl>
1952 546.5657 605.0665
1957 590.0620 676.2854
1962 658.3472 772.0492
1967 700.7706 637.1233
1972 724.0325 699.5016
1977 813.3373 713.5371
1982 855.7235 707.2358
減去后比較印度,越南
gapminder %>%
select(country, year, gdpPercap) %>%
pivot_wider(names_from = country, values_from = gdpPercap) %>%
arrange(year) %>%
mutate_at(vars(-matches("year")), ~ . - India) %>%
select(year,India,Vietnam)
year India Vietnam
<int> <dbl> <dbl>
1952 0 605.0665
1957 0 676.2854
1962 0 772.0492
1967 0 637.1233
1972 0 699.5016
1977 0 713.5371
1982 0 707.2358
我不確定代碼有什么問題?
感謝任何幫助!
這是一個行為mutate_at
,你可以切換到across
(由@RonakShah的建議),並做到:
gapminder %>%
select(country, year, gdpPercap) %>%
pivot_wider(names_from = country, values_from = gdpPercap) %>%
arrange(year) %>%
mutate(across(-matches('year'), ~ . - India)) %>%
select(year, India, Vietnam)
使用mutate_at
,您需要確保用於計算的列是數據中的最后一列 - 您可以使用relocate
移動它,如下所示:
gapminder %>%
select(country, year, gdpPercap) %>%
pivot_wider(names_from = country, values_from = gdpPercap) %>%
arrange(year) %>%
relocate(India, .after = last_col()) %>%
mutate_at(vars(-matches('year')), ~ . - India) %>%
select(year, India, Vietnam)
輸出:
# A tibble: 12 x 3
year India Vietnam
<int> <dbl> <dbl>
1 1952 0 58.5
2 1957 0 86.2
3 1962 0 114.
4 1967 0 -63.6
5 1972 0 -24.5
6 1977 0 -99.8
7 1982 0 -148.
8 1987 0 -156.
9 1992 0 -175.
10 1997 0 -72.9
11 2002 0 17.7
12 2007 0 -10.6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.