【问题标题】:Transforming a variable using the if- else if function使用 if-else if 函数转换变量
【发布时间】:2020-06-25 15:42:29
【问题描述】:

我有一个数据集,我想按他们的年份计算 z 分数。

例子:

  Year  Score
   1999   120
   1999   132
   1998   120
   1997   132
   2000   120
   2002   132
   1998   160
   1997   142
   ....etc

我想要的是:

  Year  Score  Z-Score
   1999   120  1.2
   1999   132  .01
   1998   120  -.6
   1997   132  1.1
   2000   120  -.6
   2002   132  0.5
   1998   160  2.1
   1997   142  .01

我使用了以下代码:

DF$ZScore<-if (DR$Year== 1997){
((DF$Score-220)/20)
} else if ((DR$Year== 1998){
((DF$Score-222)/19)
}...
}else{
((DF$Score-219)/21)
}

这不起作用,我不知道为什么。任何帮助表示赞赏。

【问题讨论】:

    标签: r if-statement data-wrangling


    【解决方案1】:

    为了简单起见,我使用了 gapminder 数据以及内置的缩放功能。您可能想要构建自己的函数来应用,具体取决于您想要扩展它的方式。

    这有点笨拙,但是因为您希望每年进行缩放,所以您可以按年份分组并制作嵌套数据框。 然后使用 purr,您可以在一年内进入每个 data.frame,并缩放您想要的变量。 然后您将再次取消嵌套数据,并且变量将在每年内进行缩放。

    library(tidyverse)
    library(gapminder)
    
    gapminder::gapminder %>% 
      group_by(year) %>% 
      nest() %>% 
      mutate(data = map(data, 
                        ~ mutate_at(.x, vars(lifeExp, pop), 
                                          list(scale = scale)))) %>% 
      unnest(data)
    #> # A tibble: 1,704 x 8
    #> # Groups:   year [12]
    #>     year country continent lifeExp    pop gdpPercap lifeExp_scale[,…
    #>    <int> <fct>   <fct>       <dbl>  <int>     <dbl>            <dbl>
    #>  1  1952 Afghan… Asia         28.8 8.43e6      779.           -1.66 
    #>  2  1952 Albania Europe       55.2 1.28e6     1601.            0.505
    #>  3  1952 Algeria Africa       43.1 9.28e6     2449.           -0.489
    #>  4  1952 Angola  Africa       30.0 4.23e6     3521.           -1.56 
    #>  5  1952 Argent… Americas     62.5 1.79e7     5911.            1.10 
    #>  6  1952 Austra… Oceania      69.1 8.69e6    10040.            1.64 
    #>  7  1952 Austria Europe       66.8 6.93e6     6137.            1.45 
    #>  8  1952 Bahrain Asia         50.9 1.20e5     9867.            0.154
    #>  9  1952 Bangla… Asia         37.5 4.69e7      684.           -0.947
    #> 10  1952 Belgium Europe       68   8.73e6     8343.            1.55 
    #> # … with 1,694 more rows, and 1 more variable: pop_scale[,1] <dbl>
    

    reprex package (v0.3.0) 于 2020 年 6 月 25 日创建

    【讨论】:

    • 我已经使用了 split 功能,并将我的 df 按年划分为一个列表。然后我将每个列表元素单独转换为一个 df,添加我那一年特定的新变量,然后将所有这些新的 dfs rbind 在一起。不是最快的方法,但它完成了。我一直在尝试此代码,但我似乎无法正确...不过感谢您的帮助!
    猜你喜欢
    • 2019-04-09
    • 2021-08-30
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2020-10-29
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多