创建列以填充其他列中的匹配项

时间:2019-03-11 20:35:11

标签: r match

我有一个简单的Match,但不能完全起作用。对于下面的示例数据框,我想添加一列以返回列号的值。例如:对于第1行,x的值应等于4,在第2行中,x的值应等于3,依此类推。

# create sample data frame
    c1 <- c("1","2","3")
    c2 <- c("8","1","3")
    c3 <- c("4","2","4")
    c4 <- c("1","3","5")
    df <- data.frame(c1,c2,c3,c4)
    colnames(df)[c(1:4)] <- c("CodeToMatch","Code.1","Code.2","Code.3")
    View(df)

    df <- as.data.frame(df)

# my attempt create a column at the end which populates the column location of "CodeToMatch"
    df$x <- match(df$CodeToMatch,2:4)

2 个答案:

答案 0 :(得分:2)

似乎您正在匹配数字 2:4,而不是数据帧的。另外,您不明智地进行匹配的行。这应该起作用:

const http = require('http');
const fs = require('fs');
const router = require('./routing');

http.createServer((req, res) => {
router.getFile('rest');
res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream('./views/myview.html').pipe(res);

}).listen(3000);

请注意,由于没有在匹配中包含第1列,因此在每个匹配项的末尾都添加了1。

答案 1 :(得分:1)

我不明白为什么您要创建df factor的所有列;将它们作为numeric向量会更明智。除此之外,这里是使用which

的一个选项
# Convert factors to numeric
df[] <- Map(function(x) as.numeric(as.character(x)), df)

# Find column indices of matching entries
df$x <- 1 + mapply(function(x, y) which(x == y), df[, 1], as.data.frame(t(df[, -1])))
#  CodeToMatch Code.1 Code.2 Code.3 x
#1           1      8      4      1 4
#2           2      1      2      3 3
#3           3      3      4      5 2

实际上,由于您正在执行逐行操作,因此在这里,使用预先分配好的旧for循环是没有问题的。这应该与其他*apply解决方案一样快。

# Convert factors to numeric
df[] <- Map(function(x) as.numeric(as.character(x)), df)

df$x <- 0
for (i in 1:nrow(df)) df$x[i] <- which(df[i, 1] == df[i, -1]) + 1
#  CodeToMatch Code.1 Code.2 Code.3 x
#1           1      8      4      1 4
#2           2      1      2      3 3
#3           3      3      4      5 2
相关问题