我有以下数据:
我想把这些数据加起来(例如,字母A)。对于绝对值来说,这很容易。然而,就百分比而言,我需要考虑权重。因此,我希望将具有小数位(百分比)的列与不具有小数位(百分比)的列分开。
应允许百分比列同时具有绝对数和小数。但是绝对列不允许小数位。
我该怎么做?
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)]发布于 2021-03-19 10:47:24
使用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。
https://stackoverflow.com/questions/66706457
复制相似问题