【问题标题】:Split columns into two groups. One with numbers that have decimals and one with only absolute numbers将列分成两组。一个数字有小数,一个数字只有绝对数字
【发布时间】:2021-03-19 18:47:24
【问题描述】:

我的数据如下:

我想对这些数据求和(例如字母 A-E)。对于绝对值,这很容易。但是对于百分比,我需要考虑权重。因此,我想将有小数位(百分比)的列与没有小数位的列分开。

应该允许百分比列同时包含绝对数字和小数。但是绝对列中不允许有小数位。

我应该怎么做?

DT <- structure(list(Letters = c("A", "B", "C", "D", "E"), Percentage = c(0.67, 
0.2, 0.4, 0.2, 0), Absolute_number = c(1000, 200, 0, -199, 1), 
    PercentageII = c(65.2, 1.2, 22.8, 4, 0), weights = c(2, 3, 
    3, 1, 8)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
"data.frame"))

  Letters Percentage Absolute_number PercentageII weights
  <chr>        <dbl>           <dbl>        <dbl>   <dbl>
1 A             0.67            1000         65.2       2
2 B             0.2              200          1.2       3
3 C             0.4                0         22.8       3
4 D             0.2             -199          4         1
5 E             0                  1          0         8

预期输出:

DT1 <- DT[, c("Letters","Absolute_number", "weights")]
DT2 <- DT[, c("Letters","Percentage", "PercentageII)]

【问题讨论】:

  • 我已经添加了预期的输出。

标签: r


【解决方案1】:

使用Filter

DT1 <- Filter(function(x) is.character(x) || all(x %% 1 == 0), DT)
DT2 <- Filter(function(x) is.character(x) || any(x %% 1 != 0), DT)

DT1

# A tibble: 5 x 3
#  Letters Absolute_number weights
#  <chr>             <dbl>   <dbl>
#1 A                  1000       2
#2 B                   200       3
#3 C                     0       3
#4 D                  -199       1
#5 E                     1       8

DT2
# A tibble: 5 x 3
#  Letters Percentage PercentageII
#  <chr>        <dbl>        <dbl>
#1 A             0.67         65.2
#2 B             0.2           1.2
#3 C             0.4          22.8
#4 D             0.2           4  
#5 E             0             0  

x %% 1 == 0 返回 TRUE 如果值是整数(不带小数位)。

【讨论】:

    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多