簡體   English   中英

從嵌套列表中提取值

[英]Extracting values from nested lists

假設我從假設的調查中收集了以下數據集:

name    age    homeowner    favorite_color    pets
Bill    45     Yes          Blue              (cat, dog, fish)
Mary    33     Yes          Red               (cat, dog)
Joe     55     Yes          Blue              (cat, bird, fish)
Sue     38     No           Green             (fish, bird)

每個人都能夠對他們擁有的寵物類型提供多種回應。

有沒有一種簡單的方法可以使用ggplot2創建以下的散點圖?

x axis = homeowner
y axis = favorite_color
col = pets

基本上,我希望繪制三個分類值。 我無法弄清楚如何最好地提取寵物的嵌套矢量數據。 為了簡單起見,我們假設他們只允許攜帶各種寵物。

在(是的,藍色)的交叉點,我希望看到一個抖動的情節:

  • 對於相同顏色的貓,2分
  • 相同顏色的魚2分
  • 1分為鳥
  • 1點魚

你可以在這里提供的任何幫助將非常感激 - 對r來說很新。

survey <- data.frame(name = c("Bill", "Mary", "Joe", "Sue"),
                 age = c(45, 33, 55, 38),
                 homeowner = c(rep("Yes", times = 3), "No"),
                 favorite_color = c("Blue", "Red", "Blue", "Green"),
                 pets = c("(cat, dog, fish)",
                          "(cat, dog)",
                          "(cat, bird, fish)",
                          "(fish, bird)"))
# Rebuild your data

all_pets <- c("cat", "dog", "fish", "bird")
# Specify all kinds of pets you have (Someone else may have a better way here)

name <- NULL
pets <- NULL
for (i in 1:nrow(survey)) {
  for (j in 1:length(all_pets)) {
    if (grepl(all_pets[j], survey$pets[i])) {
      name <- append(name, as.character(survey$name[i]))
      pets <- append(pets, all_pets[j])
    }
  }
}
new_survey <- data.frame(name, pets)
merged_survey <- merge(survey, new_survey, by = "name")

現在merged_survey應該擁有您需要的信息。 現在我們可以用ggplot2繪制它。

require(ggplot2)
g <- ggplot(aes(x = homeowner, y = favorite_color), data = merged_survey)
g + geom_point(aes(color = pets.y), position = position_jitter(0.1, 0.1))

在此輸入圖像描述

position_jitter函數每次都隨機抖動點,所以你可能看不到與我完全相同位置的點。 您可以通過更改position_jitter中的數字來調整抖動寬度和高度。 所有標簽都可以在以后更改,但這可能是偏離主題的。

暫無
暫無

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

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