AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-4224718

M. Beausoleil's questions

Martin Hope
M. Beausoleil
Asked: 2025-01-14 01:28:18 +0800 CST

Qual é a maneira correta de alterar as unidades de um raster para levar em conta a área de cada pixel usando terra?

  • 5

Tenho um raster para o qual quero alterar os valores para pixel-value per hectar, onde a área vem do tamanho do pixel. Então, se um pixel tem 10 ha e seu valor atual é 100 abitrary-units, agora será 10 abitrary-units/ha.

Exemplo raster:

r <- rast(nrows=18, ncols=36)
v <- 1:ncell(r)
v[200:400] <- NA
values(r) <- v

Esta função deve pegar o raster e multiplicar por 1/ha.

px2ha <- function(raster) {
  raster * 10000/prod(res(raster))
}

Que tal usar cellSize assim?

r2/cellSize(r2, unit = 'ha')

Não recebo a mesma resposta.

r2 = project(x = r, y = 'epsg:2950') # Put raster in meters 
plot((r2))
plot(px2ha(r2))
plot(r2/cellSize(r2, unit = 'ha'))

O cellSize poderia ser usado para obter o valor de pixel por área (hectar)?

  • 1 respostas
  • 49 Views
Martin Hope
M. Beausoleil
Asked: 2024-12-19 22:30:49 +0800 CST

Extraia as espécies de uma página HTML da lei canadense

  • 6

Tenho esse código para tentar extrair as espécies da lei encontrada aqui https://laws.justice.gc.ca/fra/lois/S-15.3/TexteComplet.html

No entanto, não consigo fazer com que o html_nodes encontre cada seção

  section <- div_content %>% html_nodes(xpath = paste0("//h2[contains(text(), '", header, "')]/following-sibling::div[contains(@class, 'ProvisionList')]"))

Basicamente, não consigo encontrar uma maneira de obter o conteúdo do texto e corresponder às outras seções. Tentei adicionar a
tag " " e encontrar o texto para cada seção, mas não funciona (obtenha um {xml_nodeset (0)})

Estou tentando obter os dados encontrados em div com id "425426", então, dentro do scheduleLabel, obter texto de scheduleTitleText. Preciso de outra coluna para SchedHeadL1 (que é o título das seções com as espécies) e o texto encontrado em BilingualGroupTitleText (declarando o grupo de animais ou plantas...). Então forneça uma lista aninhada de espécies (aqui estou separando as espécies do nome em francês, latim e inglês)

library(rvest)
library(dplyr)
library(stringr)

# URL of the webpage
url <- "https://laws.justice.gc.ca/fra/lois/S-15.3/TexteComplet.html"

# Read the webpage content
webpage <- read_html(url)

# Extract the div with id "425426"
div_content <- webpage %>% html_node("#425426")

# Extract the header h2 with class "scheduleTitleText" from the class "scheduleLabel" and id "h-425427"
schedule_label <- div_content %>% html_node("h2.scheduleLabel#h-425427") %>% html_text()

# Extract all h2 headers with class "SchedHeadL1"
headers <- div_content %>% html_nodes("h2.SchedHeadL1") %>% html_text()


# Use str_extract to extract the "PARTIE #" part
partie_numbers <- str_extract(headers, "PARTIE \\d+")

# Use str_remove to remove the "PARTIE #" part from the original strings
descriptions <- str_remove(headers, "PARTIE \\d+")

# Combine into a data frame
result <- data.frame(Partie = partie_numbers, Description = descriptions, stringsAsFactors = FALSE)

headers_prep = result |> 
  unite(pd, Partie, Description, sep = "<br>") |> pull(pd)

# Initialize lists to store the extracted data
group_titles <- list()
item_first <- list()
item_second <- list()
scientific_names <- list()
latin_names <- list()

# Loop through each header to extract the associated content
for (header in headers) {
  # Extract the section associated with the current header
  section <- div_content %>% html_nodes(xpath = paste0("//h2[contains(text(), '", header, "')]/following-sibling::div[contains(@class, 'ProvisionList')]"))
  
  # Extract BilingualGroupTitleText within the section
  group_title <- section %>% html_nodes(".BilingualGroupTitleText") %>% html_text()
  group_titles <- c(group_titles, group_title)
  
  # Extract BilingualItemFirst within the section
  item_first_section <- section %>% html_nodes(".BilingualItemFirst") %>% html_text()
  item_first <- c(item_first, item_first_section)
  
  # Extract BilingualItemSecond within the section
  item_second_section <- section %>% html_nodes(".BilingualItemSecond") %>% html_text()
  item_second <- c(item_second, item_second_section)
  
  # Extract otherLang (scientific names) within the section
  scientific_name_section <- section %>% html_nodes(".otherLang") %>% html_text()
  scientific_names <- c(scientific_names, scientific_name_section)
  
  # Extract scientific Latin names from BilingualItemFirst
  latin_name_section <- str_extract(item_first_section, "\\(([^)]+)\\)") %>% str_replace_all("[()]", "")
  latin_names <- c(latin_names, latin_name_section)
}

# Ensure all columns have the same length by repeating the last element if necessary
max_length <- max(length(headers), length(group_titles), length(item_first), length(item_second), length(scientific_names), length(latin_names))

schedule_label <- rep(schedule_label, length.out = max_length)
headers <- rep(headers, length.out = max_length)
group_titles <- rep(group_titles, length.out = max_length)
item_first <- rep(item_first, length.out = max_length)
item_second <- rep(item_second, length.out = max_length)
scientific_names <- rep(scientific_names, length.out = max_length)
latin_names <- rep(latin_names, length.out = max_length)

# Create a data frame
data <- data.frame(
  ScheduleLabel = schedule_label,
  Header = headers,
  GroupTitle = group_titles,
  ItemFirst = item_first,
  ItemSecond = item_second,
  ScientificName = scientific_names,
  LatinName = latin_names,
  stringsAsFactors = FALSE
)
  • 1 respostas
  • 34 Views
Martin Hope
M. Beausoleil
Asked: 2024-11-05 22:39:02 +0800 CST

lista cbind com dois elementos de lista em R

  • 6

Tenho 2 listas:

a = list(data.frame(a = 1:10, b = 21:30), data.frame(a = 11:20, b = 31:40))
b = list(data.frame(c = letters[1:10]), data.frame(c = LETTERS[1:10]))

E eu quero vinculá-los automaticamente para que a coluna c seja pareada com cada elemento na lista.

Isto é o que eu espero (manualmente)

c = list(data.frame(a = 1:10, b = 21:30, c = letters[1:10]), data.frame(a = 11:20, b = 31:40, c = LETTERS[1:10]))

Ao tentar isso,

do.call(cbind, a, b)

Eu entendo

Error in if (quote) args <- lapply(args, enquote) : 
  the condition has length > 1

Saída esperada:

c
[[1]]
    a  b c
1   1 21 a
2   2 22 b
3   3 23 c
4   4 24 d
5   5 25 e
6   6 26 f
7   7 27 g
8   8 28 h
9   9 29 i
10 10 30 j

[[2]]
    a  b c
1  11 31 A
2  12 32 B
3  13 33 C
4  14 34 D
5  15 35 E
6  16 36 F
7  17 37 G
8  18 38 H
9  19 39 I
10 20 40 J
  • 1 respostas
  • 22 Views
Martin Hope
M. Beausoleil
Asked: 2024-10-10 22:33:40 +0800 CST

Como extrair o `Geodetic CRS` ou `Projected CRS` do cabeçalho de impressão do objeto sf?

  • 5

Ao imprimir objetos sf no console, há um cabeçalho com o Geodetic CRSou Porjected CRSque tem um nome de formato agradável para o CRS. Existe uma maneira de extrair essas informações em vez de

p1 = st_point(c(7,52))
p2 = st_point(c(-30,20))
sfc = st_sfc(p1, p2, crs = 4326)
sfc
Geometry set for 2 features 
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -30 ymin: 20 xmax: 7 ymax: 52
Geodetic CRS:  WGS 84                  <- this line
POINT (7 52)
POINT (-30 20)

st_transform(sfc, 3857)
Geometry set for 2 features 
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -3339585 ymin: 2273031 xmax: 779236.4 ymax: 6800125
Projected CRS: WGS 84 / Pseudo-Mercator                  <- this line
POINT (779236.4 6800125)
POINT (-3339585 2273031)

nc = st_read(system.file("shape/nc.shp", package="sf"))
nc
Simple feature collection with 100 features and 14 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
Geodetic CRS:  NAD27                  <- this line
First 10 features:
[...]

Veja como st_crs(sfc)$inputdá "EPSG:4326"e não WGS 84. No entanto, st_crs(nc)$inputdá "NAD27", mas st_crs(st_transform(sfc, 3857))$inputdá "EPSG:3857"e nãoProjected CRS: WGS 84 / Pseudo-Mercator

Existe também o equivalente em terra para dados raster?

  • 2 respostas
  • 26 Views
Martin Hope
M. Beausoleil
Asked: 2024-10-08 23:42:57 +0800 CST

diferença de rolagem entre um código base selecionado em comparação com outro código em R

  • 5

Tenho um código onde há um cenário ( sccoluna) e um nome de código ( cdcoluna). Quero calcular a diferença entre todos os cenários para o primeiro (então cenário 2-1, 3-1, etc. Tenho vários outros cenários...). Existe uma maneira rápida de codificar qual cenário será comparado, por exemplo, se eu agora o cenário do qual todos os outros são comparados é agora o cenário 2, seria 1-2, 3-2, etc.?

Mas também quero ter certeza de que, entre os cenários, eu subtraia apenas os mesmos nomes de código ( cd), então ( sc1.cd1 - sc2.cd1), ( sc1.cd2 - sc2.cd2), etc.

Também quero a diferença percentual entre o sccenário 1 em comparação aos outros para cada código.

No momento, meu código assume que, quando comparo os cenários, eles cdestão na mesma ordem. Haveria uma maneira de comparar os cenários e o código juntos em vez de usar um subconjunto dos dados?

set.seed(123456)
vals = as.vector(mapply(FUN = rpois, n = 10, lambda = c(5, 10, 100)))
df.test = data.frame(cd = rep(1:10,3), sc = rep(1:3, each =10 ), vals)

# New empty column 
df.test$delta = NA

# Subset each scenarios and subtract for the first scenario
df.test[df.test$sc ==1,'delta'] = df.test[df.test$sc ==1,'vals']-df.test[df.test$sc ==1,'vals']
df.test[df.test$sc ==2,'delta'] = df.test[df.test$sc ==2,'vals']-df.test[df.test$sc ==1,'vals']
df.test[df.test$sc ==3,'delta'] = df.test[df.test$sc ==3,'vals']-df.test[df.test$sc ==1,'vals']

# Get difference
df.test$diff = abs(abs(df.test$delta) - df.test$vals)

# Calculate percentage
df.test$delta.perc = abs(df.test$delta) / df.test$diff +1
df.test$diff * df.test$delta.perc

# Percentage increase
df.test$delta.perc.increase = df.test$delta.perc *100
  • 2 respostas
  • 24 Views
Martin Hope
M. Beausoleil
Asked: 2024-04-23 03:24:11 +0800 CST

Por que e como consertar o Mapview não mostra todos os pontos e o st_buffer mescla algumas áreas R?

  • 6

Estou construindo um mapa com o pacote mapview. Porém, quando uso st_sample e gero pontos, alguns não são mapeados. Além disso, st_buffer mescla algumas áreas (onde deveriam estar separadas).

library(sf)
library(mapview)
library(magrittr)
set.seed(145)

chemins.32188 = st_zm(chemins2) %>% st_transform(crs = 32188)

rd.pts.sentiers <- st_sample(x = chemins.32188, size = 10)

buff.pt = st_buffer(x = rd.pts.sentiers, 
                    dist = units::set_units(x = 100, 
                                           value = "m"))
mapviewOptions(fgb = FALSE)
mapview(chemins.32188) + 
  mapview(rd.pts.sentiers) +
  mapview(buff.pt)

insira a descrição da imagem aqui

Quando uso plot, funciona... mas o buffer ainda está mesclado.

plot(chemins.32188$geom) 
plot(buff.pt, add= TRUE, col = scales::alpha("blue", .5))
plot(rd.pts.sentiers, add= TRUE, pch = 19, col = "red")

insira a descrição da imagem aqui

Estes são os dados

chemins2 = structure(list(Name = "Path Measure", description = NA_character_, 
               timestamp = structure(NA_real_, class = c("POSIXct", "POSIXt"
               )), begin = structure(NA_real_, class = c("POSIXct", "POSIXt"
               )), end = structure(NA_real_, class = c("POSIXct", "POSIXt"
               )), altitudeMode = NA_character_, tessellate = -1L, extrude = 0L, 
               visibility = -1L, drawOrder = NA_integer_, icon = NA_character_, 
               sentier = NA_character_, layer = "path Parc — Path Measure", 
               path = "~/Desktop/path Parc.kml|layername=Path Measure|geometrytype=LineString25D|uniqueGeometryType=yes", 
               geom = structure(list(structure(list(structure(c(299434.130314458, 
                                                                300531.43655987, 299434.130314458, 5046816.92873926, 5047257.53966348, 
                                                                5046816.92873926), dim = 3:2), structure(c(299434.130314458, 
                                                                                                           300401.157828111, 299434.130314458, 5046816.92873926, 5046249.12770288, 
                                                                                                           5046816.92873926), dim = 3:2)), class = c("XY", "MULTILINESTRING", 
                                                                                                                                                     "sfg"))), n_empty = 0L, crs = structure(list(input = "EPSG:32188", 
                                                                                                                                                                                                  wkt = "PROJCRS[\"NAD83 / MTM zone 8\",\n    BASEGEOGCRS[\"NAD83\",\n        DATUM[\"North American Datum 1983\",\n            ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n                LENGTHUNIT[\"metre\",1]]],\n        PRIMEM[\"Greenwich\",0,\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n        ID[\"EPSG\",4269]],\n    CONVERSION[\"MTM zone 8\",\n        METHOD[\"Transverse Mercator\",\n            ID[\"EPSG\",9807]],\n        PARAMETER[\"Latitude of natural origin\",0,\n            ANGLEUNIT[\"degree\",0.0174532925199433],\n            ID[\"EPSG\",8801]],\n        PARAMETER[\"Longitude of natural origin\",-73.5,\n            ANGLEUNIT[\"degree\",0.0174532925199433],\n            ID[\"EPSG\",8802]],\n        PARAMETER[\"Scale factor at natural origin\",0.9999,\n            SCALEUNIT[\"unity\",1],\n            ID[\"EPSG\",8805]],\n        PARAMETER[\"False easting\",304800,\n            LENGTHUNIT[\"metre\",1],\n            ID[\"EPSG\",8806]],\n        PARAMETER[\"False northing\",0,\n            LENGTHUNIT[\"metre\",1],\n            ID[\"EPSG\",8807]]],\n    CS[Cartesian,2],\n        AXIS[\"easting (E(X))\",east,\n            ORDER[1],\n            LENGTHUNIT[\"metre\",1]],\n        AXIS[\"northing (N(Y))\",north,\n            ORDER[2],\n            LENGTHUNIT[\"metre\",1]],\n    USAGE[\n        SCOPE[\"Engineering survey, topographic mapping.\"],\n        AREA[\"Canada - Quebec between 75°W and 72°W.; Canada - Ontario - east of 75°W.\"],\n        BBOX[44.98,-75,62.53,-72]],\n    ID[\"EPSG\",32188]]"), class = "crs"), class = c("sfc_MULTILINESTRING", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      "sfc"), precision = 0, bbox = structure(c(xmin = 299434.130314458, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                ymin = 5046249.12770288, xmax = 300531.43655987, ymax = 5047257.53966348
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      ), class = "bbox"))), row.names = 1L, sf_column = "geom", agr = structure(c(Name = NA_integer_, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  description = NA_integer_, timestamp = NA_integer_, begin = NA_integer_, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  end = NA_integer_, altitudeMode = NA_integer_, tessellate = NA_integer_, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  extrude = NA_integer_, visibility = NA_integer_, drawOrder = NA_integer_, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  icon = NA_integer_, sentier = NA_integer_, layer = NA_integer_, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  path = NA_integer_), class = "factor", levels = c("constant", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "aggregate", "identity")), class = c("sf", "data.frame"))
  • 1 respostas
  • 16 Views
Martin Hope
M. Beausoleil
Asked: 2024-03-15 04:53:56 +0800 CST

Combine dataframes da lista aninhada em R

  • 5

Eu tenho uma lista nomeada de dados que contém quadros de dados nomeados.

mlst = list(test = list(df = data.frame(x = 1:10, y = 21:30), list(c(1:2))),
            test2 = list(df = data.frame(x = 1:10, y = 21:30), list(c(1:2))))
mlst$test$df
mlst$test2$df

A função do.call(rbind,mlst)não funciona porque não capta apenas os frames de dados. Como eu poderia vincular as linhas apenas dos dataframes sem um loop for?

  • 1 respostas
  • 33 Views
Martin Hope
M. Beausoleil
Asked: 2024-03-15 00:05:28 +0800 CST

Extraia informações hierárquicas do cabeçalho (h2, h3, tabelas) com descanso

  • 6

Neste site https://www.quebec.ca/agriculture-environnement-et-ressources-naturelles/faune/gestion-faune-habitats-fauniques/especes-fauniques-menacees-vulnerables/liste , existem tabelas de espécies que eu gostaria de extrair.

library(rvest)
sp.list = "https://www.quebec.ca/agriculture-environnement-et-ressources-naturelles/faune/gestion-faune-habitats-fauniques/especes-fauniques-menacees-vulnerables/liste"
# Get website
wp.list = read_html(species.list)
# Extract name of sections
headers = wp.list %>%  html_elements("h3") %>% html_text2() %>%   .[1:24]
# Get tables
tab = read_html(sp.list) %>% html_table(header = TRUE)
# Name tables
names(tab) = headers
# Combine tables
tab.gr = dplyr::bind_rows(tab, .id = "group")

Que dá:

tab.gr
# A tibble: 180 × 3
   group      Espèce                     `Nom latin`             
   <chr>      <chr>                      <chr>                   
 1 Mollusques Anodonte du gaspareau      Utterbackiana implicata 
 2 Mollusques Obovarie olivâtre          Obovaria olivaria       
 3 Insectes   Bourdon à tache rousse     Bombus affinis          
 4 Insectes   Coccinelle à neuf points   Coccinella novemnotata

Consegui obter os cabeçalhos das seções h2, mas não consigo associá-los a cada h3seção

get.section = wp.list %>%  html_nodes('.frame, .frame-default, .frame-type-textmedia, .frame-layout-0')
pas.dans.cette.page = !grepl(pattern = "Dans cette", x = get.section)
subset.listes = get.section[pas.dans.cette.page]
sections.tables = subset.listes[grep(pattern = "Liste des esp", x = subset.listes)]
sections.tables %>%  html_elements("h2") %>%   html_text2()
[1] "Liste des espèces menacées"                                                   
[2] "Liste des espèces vulnérables"                                                
[3] "Liste des espèces susceptibles d’être désignées comme menacées ou vulnérables"

Como então eu poderia obter o cabeçalho (por exemplo, "Liste des espèces menacées") e seus grupos (por exemplo, "Mollusques") com suas tabelas?

  • 1 respostas
  • 17 Views
Martin Hope
M. Beausoleil
Asked: 2024-01-15 21:48:49 +0800 CST

Como criar subconjuntos de várias colunas usando uma lista ou um quadro de dados com os valores a serem subconjuntos?

  • 9

Eu tenho uma lista (com número ímpar de elementos):

my.list = list(col1 = c("CC", "CT", "TT"), 
     col2 = c("GG", "GT"), 
     col3 = c("CC", "CT"),
     col4 = c("CC", "CG", "GG"), 
     col5 = c("AC", "CC"),
     col6 = "GG")

$col1
[1] "CC" "CT" "TT"

$col2
[1] "GG" "GT"

$col3
[1] "CC" "CT"

$col4
[1] "CC" "CG" "GG"

$col5
[1] "AC" "CC"

$col6
[1] "GG"

Que pode ser transformado em um quadro de dados:

mylist.df = plyr::ldply(my.list, rbind)
names(mylist.df) <- c("cols","g1", "g2", "g3")

E quero criar um subconjunto do quadro de dados abaixo usando mylistou mylist.df. Basicamente, quero manter todas as linhas que tenham pelo menos um elemento de cada valor em mylist:

df.to.subset = structure(list(IDs = c("ID1", "ID2", "ID3", "ID4", "ID5", "ID6"), 
               gr = c("gr1", "gr1", "gr1", "gr1", "gr1", "gr1"), 
               var = c(-3.451, -3.469, -3.837, -3.344, -3.904, -3.943), 
               col1 = structure(c(1L, 2L, 3L, 1L, 2L, 2L), levels = c("CC", "CT", "TT"), class = "factor"), 
               col2 = structure(c(1L, 1L, 2L, 3L, 3L, 3L), levels = c("GG", "GT", "TT"), class = "factor"), 
               col3 = structure(c(1L, 2L, 1L, 1L, 1L, 1L), levels = c("CC", "CT"), class = "factor"), 
               col4 = structure(c(2L, 2L, 2L, 2L, 2L, 2L), levels = c("CC", "CG", "GG"), class = "factor"), 
               col5 = structure(c(1L, 2L, 2L, 2L, 2L, 2L), levels = c("AC", "CC"), class = "factor"), 
               col6 = structure(c(1L, 1L, 2L, 1L, 1L, 1L), levels = c("GG","AA"), class = "factor")), 
          row.names = c(NA, 
                        -6L), class = c("tbl_df", "tbl", "data.frame"))

  IDs   gr      var col1  col2  col3  col4  col5  col6 
  <chr> <chr> <dbl> <fct> <fct> <fct> <fct> <fct> <fct>
1 ID1   gr1   -3.45 CC    GG    CC    CG    AC    GG   
2 ID2   gr1   -3.47 CT    GG    CT    CG    CC    GG   
3 ID3   gr1   -3.84 TT    GT    CC    CG    CC    AA   
4 ID4   gr1   -3.34 CC    TT    CC    CG    CC    GG   
5 ID5   gr1   -3.90 CT    TT    CC    CG    CC    GG   
6 ID6   gr1   -3.94 CT    TT    CC    CG    CC    GG   

(O resultado final seria)

  IDs   gr      var col1  col2  col3  col4  col5  col6 
  ID1   gr1   -3.45 CC    GG    CC    CG    AC    GG   
  ID2   gr1   -3.47 CT    GG    CT    CG    CC    GG   

Além disso, gostaria de nivelar novamente cada coluna para df.to.subsetcorresponder aos níveis deste quadro de dados:

factor.levels.cols = structure(list(cols = c("col1", "col2", "col3", "col4", "col5", "col6"), 
               g1 = c("CC", "GG", "CC", "CC", "AA", "AA"), 
               g2 = c("CT", "GT", "CT", "CG", "AC", "AG"), 
               g3 = c("TT", "TT", "TT", "GG", "CC", "GG")), 
          row.names = c(NA, 6L), class = "data.frame")

  cols g1 g2 g3
1 col1 CC CT TT
2 col2 GG GT TT
3 col3 CC CT TT
4 col4 CC CG GG
5 col5 AA AC CC
6 col6 AA AG GG

Um loop for é obrigatório aqui ou existe uma maneira de torná-lo mais rápido? Tenho mais de 1.000.000 de entradas para modificar.

  • 3 respostas
  • 62 Views
Martin Hope
M. Beausoleil
Asked: 2023-11-16 23:27:44 +0800 CST

Como usar ggplot2 e facet_wrap mas não descartar fatores dentro de um grupo no eixo x?

  • 7

Quero usar facet_wrap para traçar valores diferentes no eixo x para grupos diferentes. Porém, ao usar scale = "free_x", mostra valores únicos dentro de cada grupo. Veja exemplo abaixo:

library(ggplot2)
set.seed(1234)
nb = rep(LETTERS[1:3],4)
expand.grid(LETTERS[1:3], 1:3)
df = data.frame(ps = paste(rep(c("ps1","gc1"),6)),
                cr = rep(LETTERS[1:3],4),
                id = rep(x = month.abb[1:4], each = 3));df
df = df[order(df$ps),]
df[df$ps == "ps1","cr"] <- sample(LETTERS[4:6], size = 6, replace = TRUE)
df.all = rbind(df,df,df,df,df,df)
df.all$val = rnorm(n = nrow(df.all))

ggplot(df.all, 
       aes(x = cr,
           y = val)) + 
  geom_violin() +
  facet_wrap(vars(ps, id), 
             scales = "free_x",
             ncol = 4) +
  geom_point(position = position_jitter(width = 0.1, height = 0.1), 
             alpha= .3)

Na imagem aqui (que é a saída do código acima), adicionei os níveis que faltavam. Basicamente, existe o grupo "gc1" onde eu gostaria que os níveis não caíssem. Mas também não quero que os níveis do "ps1" apareçam no "gc1". Então, no final, gc1 deve mostrar apenas os níveis A, B, C e ps1 deve mostrar apenas D, E e F. Existe uma maneira de fazer isso?

insira a descrição da imagem aqui

  • 2 respostas
  • 40 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve