簡體   English   中英

操作數據框(使用R)

[英]Manipulating a dataframe (with R)

為了實現我的分析,我有一個艱巨的目標。 據我所知,沒有類似的問題。 我在Excel中有一個很長的數據框,在R環境中可以用一種更簡單的形式在此處復制它:

A1 <- cbind("sp1","sp2","sp3", "sp4", "sp7", "sp8") 
A2 <- cbind("sp1","sp3", "sp4", "sp7", "sp9") 
A3 <- cbind("sp5","sp6","sp7", "sp10") 
A4 <- cbind("sp1","sp2","sp7", "sp9", "sp10") 
A5 <- cbind("sp3","sp4") 

max_row <- 6

A1 <- c(A1, rep(NA, max_row - length(A1)))
A2 <- c(A2, rep(NA, max_row - length(A2))) 
A3 <- c(A3, rep(NA, max_row - length(A3))) 
A4 <- c(A4, rep(NA, max_row - length(A4))) 
A5 <- c(A5, rep(NA, max_row - length(A5))) 
df <-cbind(A1,A2, A3, A4, A5)
df <- as.data.frame(df)
df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)

為了更好地理解我工作的環境,“ sp”是物種,A *是我檢測到給定物種的位置。

我想將此數據幀轉換為另一個結構如下:

我想以自動化方式獲取的數據框

第一列包含地點的名稱,接下來的是所有物種的名稱(顯然,僅重復了一次)。 然后,我需要在給定站點中為存在設置“ 1”,為不存在設置“ 0”。

我花了很多時間試圖達到我的目標,但是對於我的R語法能力來說,這是一個太復雜的問題。

有人可以幫助我嗎?

您可以長格式收集數據以進行處理,並添加一欄來顯示站點上是否存在物種。 然后使用reshape2::dcast將數據擴展為以下格式:

library(tidyverse)
library(reshape2)

df %>% gather(Site, Species) %>%
  filter(!is.na(Species)) %>%
  mutate(value = 1) %>%      #Species are present on a site
  dcast(Site~Species, value.var = "value", fill = 0)

#   Site sp1 sp10 sp2 sp3 sp4 sp5 sp6 sp7 sp8 sp9
# 1   A1   1    0   1   1   1   0   0   1   1   0
# 2   A2   1    0   0   1   1   0   0   1   0   1
# 3   A3   0    1   0   0   0   1   1   1   0   0
# 4   A4   1    1   1   0   0   0   0   1   0   1
# 5   A5   0    0   0   1   1   0   0   0   0   0  

您可以使用tidyverse gatherspread

library(tidyverse)

df %>%
  gather(A, sp) %>%
  filter(!is.na(sp)) %>%
  group_by(A, sp) %>%
  count() %>%
  spread(sp, n) %>%
  replace(., is.na(.), 0)

  # A tibble: 5 x 11
# Groups:   A [5]
  A       sp1  sp10   sp2   sp3   sp4   sp5   sp6   sp7   sp8   sp9
* <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A1       1.    0.    1.    1.    1.    0.    0.    1.    1.    0.
2 A2       1.    0.    0.    1.    1.    0.    0.    1.    0.    1.
3 A3       0.    1.    0.    0.    0.    1.    1.    1.    0.    0.
4 A4       1.    1.    1.    0.    0.    0.    0.    1.    0.    1.
5 A5       0.    0.    0.    1.    1.    0.    0.    0.    0.    0.

暫無
暫無

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

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