在data.frame中查找字符串 [英] Find string in data.frame

查看:64
本文介绍了在data.frame中查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在data.frame中搜索字符串?作为一个最小的示例,如何在此data.frame中找到马的位置(列和行)?

How do I search for a string in a data.frame? As a minimal example, how do I find the locations (columns and rows) of 'horse' in this data.frame?

> 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

...因此第4行和第5行的顺序错误。任何可以让我识别出马的输出都已移至第5行的级别列和长度第4行中的列是好的。也许:

... so row 4 and 5 have the wrong order. Any output that would allow me to identify that 'horse' has shifted to the level column in row 5 and to the length column in row 4 is good. Maybe:

> magic_function(df, 'horse')
col       row
'animal', 2
'animal', 3
'length', 4
'level',  5

这就是我要使用的内容:我有一个非常大的数据框(大约60列, 20.000行),其中某些行被弄乱了。它太大了,无法识别可能导致订单错误的其他方式,因此搜索会很好。我将使用此信息将数据移动到这些行的正确列中。

Here's what I want to use this for: I have a very large data frame (around 60 columns, 20.000 rows) in which some columns are messed up for some rows. It's too large to eyeball in order to identify the different ways that order can be wrong, so searching would be nice. I will use this info to move data to the correct columns for these rows.

推荐答案

那怎么办:

which(df == "horse", arr.ind = TRUE)
#      row col
# [1,]   2   1
# [2,]   3   1
# [3,]   5   2
# [4,]   4   3

这篇关于在data.frame中查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆