Jon*_*løv 8 string r dataframe
如何在data.frame中搜索字符串?作为一个最小的例子,我如何在这个data.frame中找到'horse'的位置(列和行)?
> df = data.frame(animal=c('goat','horse','horse','two', 'five'), level=c('five','one','three',30,'horse'), length=c(10, 20, 30, 'horse', 'eight'))
> df
animal level length
1 goat five 10
2 horse one 20
3 horse three 30
4 two 30 horse
5 five horse eight
Run Code Online (Sandbox Code Playgroud)
...所以第4行和第5行的顺序错误.任何允许我识别'horse'已经转移到level第5行的length列和第4行的列的输出都是好的.也许:
> magic_function(df, 'horse')
col row
'animal', 2
'animal', 3
'length', 4
'level', 5
Run Code Online (Sandbox Code Playgroud)
以下是我想要使用的内容:我有一个非常大的数据框(大约60列,20.000行),其中一些列混淆了一些行.为了找出订单错误的不同方式,眼球太大了,所以搜索会很好.我将使用此信息将数据移动到这些行的正确列.
tho*_*hal 11
关于什么:
which(df == "horse", arr.ind = TRUE)
# row col
# [1,] 2 1
# [2,] 3 1
# [3,] 5 2
# [4,] 4 3
Run Code Online (Sandbox Code Playgroud)
另一种方式:
l <- sapply(colnames(df), function(x) grep("horse", df[,x]))
$animal
[1] 2 3
$level
[1] 5
$length
[1] 4
Run Code Online (Sandbox Code Playgroud)
如果您希望输出为矩阵:
sapply(l,'[',1:max(lengths(l)))
animal level length
[1,] 2 5 4
[2,] 3 NA NA
Run Code Online (Sandbox Code Playgroud)