簡體   English   中英

根據與 R 中的行和列/數據框不同的現有行分配標題

[英]assign headers based on existing row that is not the same row and column / dataframe in R

題。 如何提取將成為標題的行號? 我想我可以使用索引號將該行指定為標題。

標題是 c(a,b,c)

數據6*4矩陣

v1 v2 v3 v4 #header
d a b c #headera,b,c
d 1 1 1
d 1 1 1
a b c e #headera,b,c
2 2 2 e
2 2 2 e

輸出4*3矩陣

a b c #header
1 1 1
1 1 1
2 2 2
2 2 2

我的代碼..

str_which(df, 'a') #idetify row number

根據您上面寫的內容,您需要依次過濾包含 'a'、'b'、'c' 字母的行,這意味着該序列可能從v1v2 今后,我相信這將解決您的問題:


# create an indexed data frame
df.with.index <- mutate(df, IDX = 1:n())

# filter the data frame by the condition above, and output the index
dplyr::filter(df.with.index,
              (v2 == 'a' & v3 == 'b' & v4 == 'c')
              | (v1 == 'a' & v2 == 'b' & v3 == 'c'))$IDX

這將導致:

[1] 1 4

如果您需要測試行是否僅包含字母“a”,您可能需要使用以下命令:

dplyr::filter(df.with.index, (v1 == 'a' | v2 == 'a' | v3 == 'a' | v4 == 'a'))$IDX

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM