用分别的和替换分隔的数据帧值

时间:2015-12-15 23:27:41

标签: r replace

如何更换" 0 | 0"," 0 | 1"," 1 | 0"," 1 | 1" ," 2 | 0"用" 0"," 1"," 1"," 2"," 2"分别在数据框架?例如:

df2 <- data.frame(A = c("0", "2", "1"), B = c("2", "0", "1"))

预期结果是每对的总和,即:

void show(const double a[], unsigned els) {  // a is const
size_t index = 0;

for (index = 0; index < els; index++) {
    cin >> a[index];  // you're trying to write to a const array
    }

3 个答案:

答案 0 :(得分:4)

这是一个尝试。如果您需要第二个数据框,请先使用private static Point checkLineLeft(Point point, Mat intensive) { int minX = point.getX() - intensive.width()*0.2; int y = point.getY(); for (int x = point.getX() - 1 ; x > minX && x >= 0 ; x--) { if (isCorrectPoint(intensive, x, y)) { return new Point(x, y); } } return new Point(-1, -1); } private static boolean isCorrectPoint(Mat intensive, int x, int y) { return intensity.get(y, x)[0] > 100 && intensity.get(y, x)[2] < 50; } 以便您拥有旧版本(df2 <- df1将是旧版本),或使用df2将其打包并调用{ {1}}。

as.data.frame()

给出了

df2

你想要的结果显示了角色值,但是在获得总和之后再次强制回到角色似乎很愚蠢。因此我将它们保留为数字。你可能会发现这对以后有益。

修改1:或者,您可以将df1[] <- lapply(df1, function(x) { ## split the column on '|' s <- strsplit(as.character(x), "|", fixed = TRUE) ## coerce to numeric and find the sum vapply(s, function(a) sum(as.numeric(a)), 1) }) 替换为df1 # A B # 1 0 2 # 2 2 0 # 3 1 1 并减少写作。

strsplit()

编辑2:这是第三种方法,有点整洁,不使用任何嵌套循环。我们将数据重新读取为分隔符,然后使用scan()属性对其进行重组。

df1[] <- lapply(df1, function(x) { 
    vapply(as.character(x), function(a) sum(scan(text = a, sep = "|")), 1)
})

或者为了好玩,这个荒谬的单行版同样的东西......

df1

答案 1 :(得分:2)

df1_split <- lapply(df1, function(x){strsplit(as.character(x), split = "\\|")})
df1_sum <- lapply(df1_split, lapply, function(x) sum(as.numeric(x)))
as.data.frame(lapply(df1_sum, unlist))

哪个给你

  A B
1 0 2
2 2 0
3 1 1

答案 2 :(得分:0)

还可以使用函数gsub和包dplyr

df1 <- data.frame(A = c("0|0", "1|1", "0|1"), B = c("2|0", "0|0", "1|0"),
                  stringsAsFactors = FALSE)
library(dplyr)
df1 %>% mutate(A=as.numeric(gsub("\\|.+", "", A))+as.numeric(gsub(".+\\|", "", A)), 
               B=as.numeric(gsub("\\|.+", "", B))+as.numeric(gsub(".+\\|", "", B)))
#   A B
# 1 0 2
# 2 2 0
# 3 1 1