Posts by Willian Vieira • 3,675 points
78 posts
-
7
votes2
answers50
viewsA: How to relate a column to a dictionary in R?
The problem is that you reversed the arguments of valores and nomes when you created the object dicionario. It would be right: dicionario <- setNames(corpo_programa$situacao, corpo_programa$nome)…
-
0
votes1
answer49
viewsA: Problems Adjusting Linear Regression in Stan
From what I understand from your model, you’re defining a class real while you should be wearing vector for the objects x, y and mu: data{ int n; vector[n] y; vector[n] x; } parameters{ real alpha;…
-
5
votes1
answer62
viewsA: 'The number of derivatives returned by func() (2) must Equal the length of the initial conditions vector (4)' in R
I think the problem is how you define the initial values and parameters within the model function. Looking at the package documentation deSolve and following the guidelines on how to build the model…
-
4
votes1
answer63
viewsA: Function to find complete word, but independent of position in string
You can use \b or \<\> to limit the beginning and end of a word: grep('\\balho\\b', c("produção e trabalho","fabricante de alho", "alho brasileiro","tem alho aqui"), value = TRUE)…
-
7
votes2
answers72
viewsA: How to turn a column with a sentence per row into a column where each row is a word of these phrases?
If I understand what you want as a result: data.frame(palavras = unlist(strsplit(palavras_cnae_agro$palavras, ' '))) EDITED Instead of using ' ' as space, it is recommended to use syntax \\s+ of the…
-
6
votes1
answer44
viewsA: Masked objects when loaded. Does this make it impossible for the package to perform its function? How to resolve?
You can specify from which package to use the function with :: rgdal::buffer() raster::buffer() It is always recommended to specify from which package we are using the function as shown above.…
ranswered Willian Vieira 3,675 -
3
votes1
answer363
viewsA: R - How to turn values into percentages using Data.table?
If I understand correctly you can do it in two steps: # quantidade por região d[, total := sum(Quantidade), by = Região] # frequência d[, Freq := Quantidade/total*100] # rm columa d[, total := NULL]…
ranswered Willian Vieira 3,675 -
1
votes2
answers57
viewsA: How to replicate a line with a difference of names on it? R
You can use a loop for() with the function paste(): a <- function(input) { for(i in 1:length(input)) { res <- input[i] * 4.95 + input[i] print(paste0('resultado x', i)) print(res) } } a(input…
ranswered Willian Vieira 3,675 -
5
votes3
answers115
viewsQ: Regular expression of citations in R
I would like to extract all reference keys I use in a document markdown beginning with the character @. Here is an example of the different ways I can quote a document using this key: line <-…
-
5
votes1
answer111
viewsA: Graphic with animation in R
If you put the code to produce the image within the function saveGIF() works: lam <- seq(1e-3, 1000, length.out = 100) animation::saveGIF( { for(i in 1:length(lam)){ plot(x, y, col = "grey", pch…
-
2
votes3
answers55
viewsA: Convert a factor (of real numbers) into a numerical vector
From what I understand, the problem is that you are using a comma separator instead of the dot. Converting a comma to a point, and then to a number vector is an option: df$var <-…
ranswered Willian Vieira 3,675 -
2
votes1
answer125
viewsA: Formatting Titles in Table of Contents Rmarkdown (R)
You can add css by code Chuck (or in another document style.css if it is too large) to change the document style. Remembering that it is easier to format the class (in your case h2) that format you…
-
1
votes2
answers92
viewsA: A - How to display repeat progress ? And processing time?
For the first question, just add nrow(df) at each stage of the repeat. For the second question, I followed the same logic as the first question using the function system.time(): totalRows <- 0…
-
2
votes1
answer64
viewsA: Converting from HTML/CSS to pdf using pandoc in R
In general way Pandoc will use LateX to convert to pdf. One option is to configure the style in language LateX. So that Pandoc can interpret css as style, you will need to install wkhtmltopdf:…
-
5
votes1
answer732
viewsA: How to convert million units into dozens unit in R?
You can use the package humanize: Numero = 80000000000 humanize::count_as_word(Numero) # [1] "80.0 billion"…
-
3
votes1
answer380
viewsA: create PDF dynamically in Rmarkdown
I will show here two options through an example. The example will be a data frame with two columns. For each row of the column, I will create a Rmd that will make the sum of the two columns. Option…
-
1
votes2
answers942
viewsA: Loop R to find the highest value in a column
You don’t need to create the function to find the lowest value, they already exist: min() # para retornar o menor valor which.min() # para retornar a posição do menor valor in your case it would be…
ranswered Willian Vieira 3,675 -
4
votes2
answers1298
viewsA: Date and Time in the same field, how to separate in R?
You can use the function strptime() and others more that I put in the example: x <- "23:02:1989 14:22" dataHora <-strptime(x, "%d:%m:%Y %H:%M") # converte para o formato adequado # [1]…
ranswered Willian Vieira 3,675 -
3
votes2
answers233
viewsA: How do I chart the production function of Cobb-Douglas in the R?
Here is one of the infinite possibilities to accomplish what you want: # criar uma função P = function(L, K) { return(1.01 * L^0.75 * K^0.25 ) } # Variáveis L = K = 0:300 # definir amostra de uma…
ranswered Willian Vieira 3,675 -
4
votes2
answers145
viewsA: Operations with Data Frame
You can use the same function subset() with the operator ! which means a denial. More information here. dados = subset(dados, !(VALOR1==0&VALOR2==0&VALOR3==0&VALOR4==0))…
ranswered Willian Vieira 3,675 -
5
votes1
answer60
viewsA: Change colors on the chart
For the first question, you can provide a color vector for the argument col. In this example I will leave the main line black and the others in gray: cor = c('black', rep('gray', 4)) For the second…
ranswered Willian Vieira 3,675 -
5
votes2
answers117
viewsA: I could not resolve the error: The condition has length > 1 and only the first element will be used
The problem is that you’re comparing two vectors, equating the condition if(x > y) asks only one value for x and y. If instead of passing only one value you pass an array of values, the condition…
-
0
votes1
answer289
viewsA: Rescue indexes from my data elements.frame
set.seed(42) Suppose you have the following data.frame: let = rep(letters[1:5], 3) valor = rnorm(length(let)) dat = data.frame(let, valor) # let valor # 1 a 1.37095845 # 2 b -0.56469817 # 3 c…
-
3
votes3
answers673
viewsA: How to go through the data.frame cases using `dplyr`?
An option using the package data.table: library(data.table) #transformar o data frame em data.table data_2 = as.data.table(data_1) # criar os indices para indicar que o cálculo será feito para cada…
ranswered Willian Vieira 3,675 -
6
votes1
answer371
viewsA: How to use letters instead of numbers within the LETTERS array?
A (long) option would be: LETTERS[which("A" == LETTERS):which("J" == LETTERS)] # [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" Within a function: lettersSeq = function(primeira, segunda) {…
ranswered Willian Vieira 3,675 -
4
votes2
answers53
viewsA: How to know in which position an unknown is located in a vector?
Take a look at the function which(): a=c(10,9,8,7) b<-max(a) a[b] which(a == b) # [1] 1 Other options is the function match(): match(b, a) # [1] 1…
ranswered Willian Vieira 3,675 -
4
votes2
answers504
viewsA: Replace ")" by space using str_replace_all() in R
You can use the function gsub(): gsub("\\(|\\)", " ", cadastros$telefone) # [1] " 61 99831-9482" "32 8976 2913" "62-9661-1234" "15-40192.5812" The first argument you provide the pattern you want to…
-
5
votes2
answers114
viewsA: How to create one vector from another in r?
You can use the vector coef to index vector elements fixo: coef <- c(1,4,10) # criar vetor de zeros fixo <- rep(0, max(coef)) # adicionar NA para cada coef fixo[coef] <- NA fixo # [1] NA 0…
ranswered Willian Vieira 3,675 -
5
votes1
answer59
viewsA: Doubt how to measure the number of words between two specific words in a string in R
One possibility is to use the operator %in% to find the position of palavra1 and of palavra2 and then calculate the distance between the two: t <- "bom dia posso ajudar nao viu zunkz sabe nao…
ranswered Willian Vieira 3,675 -
4
votes1
answer404
viewsA: How do you return multiple objects in a function of r?
If you want to return more than one object, you must use one list(): f <- function(a, b, c) { d <- a + (b * c) return(list(a = a, b = b, c = c, d = d)) } f(2, 4, 6) # $a # [1] 2 # # $b # [1] 4…
-
2
votes1
answer128
viewsA: Export multiple. csv files in R
I believe the problem is in the indexing you use: $. We can access each element of a list with $ and with [[]]: lista$dados1 # aa bb # 1 1 1 # 2 2 2 # 3 3 3 # 4 4 4 # 5 5 5 # 6 6 6 # 7 7 7…
ranswered Willian Vieira 3,675 -
1
votes1
answer1104
viewsA: Run a file . R within another code in R
Makefile acts as a chain of rules where you must determine the target which is usually the object you want to create (in this case a pdf file), the dependencies of this target that are necessary to…
-
1
votes2
answers64
viewsA: Automatically add all Environment elements to a list
Beyond the function ls(), you need the function get() x <- rnorm(10) y <- rnorm(20) z <- rnorm(30) Example of the use of get(): objetos <- ls() objetos[1] # [1] "a" get(objetos[1]) #[1]…
-
6
votes1
answer204
viewsA: Export data from Google Sheets to R
You can use the package googlesheets, here will a link demonstrating an example of using this package. To find other packages with keywords that we don’t know yet, besides searching on google, there…
-
3
votes1
answer36
viewsA: How to create a command to choose linearization alternatives
An option would be to create a function with the option ch: estimativa <- function(ch) { # testes if(!ch %in% c(1:4)) stop("'ch' deve conter um valor entre 1 e 4") # "Estimativas para "CHUTE" # 1…
ranswered Willian Vieira 3,675 -
6
votes2
answers200
viewsA: How to create a Stopwords using R
To complement the @Thiago Fernandes response, you can find similar patterns using the function grep(): dataset[grep('prog', dataset$funcao), 'funcao'] # [1] programador prog. The function grep()…
-
2
votes2
answers151
viewsA: Perform the tapply function for multiple variables on a dataframe (with pairwise.t.test)
Here is an option, you have to set the position of the variables you want to apply the test (varNames) and then apply the sapply: # definir variáveis para o teste varNames <- names(seguro1)[2:4]…
-
5
votes1
answer653
viewsA: How to check if all values are equal in a vector in r
You can simply compare the first element with each element using ==. This will return a vector of TRUE or FALSE and all test whether all elements of this vector are equal to TRUE (all is the same as…
-
2
votes1
answer68
viewsA: How can I assign a variable to a table?
Your data is in the form of a comma-separated file (csv), but with quotation marks for the values. I believe a simple read.csv will not function (other suggestions are welcome). One solution will be…
-
2
votes1
answer230
viewsA: How to ignore and not iterate over a for in R
You can use the option while() in the sense that it will try several times until it does not get an error, keeping the value of i fixed: for (j in 1:length(pp)) { for (i in 1:100) { n0 <-…
ranswered Willian Vieira 3,675 -
4
votes1
answer48
viewsA: Lapply to pull ADF test results on R
First question: means come repeated because you repeat this value with the function rep(). Taking this function will return only one value per list: resultlist <- lapply(mylist, function(x)…
ranswered Willian Vieira 3,675 -
3
votes2
answers119
viewsA: Convert all Environment files to '.Rda' and then load them at once with a loop
Here’s a more automatic response if you have many data frames and don’t want to write each one’s name manually. First part explaining how to save all Environment data frames: # criar dados (apenas…
ranswered Willian Vieira 3,675 -
2
votes2
answers53
viewsA: Generate multiple graphics in a loop using X11() and two different indices in R
Just put the loop for with the j before the x11(): for(j in 1:10) { x11() par(mfrow=c(3,2)) for (i in 1:5) { plot.ts(mylist[[i]][[j]]) } }…
ranswered Willian Vieira 3,675 -
7
votes1
answer579
viewsA: creation of gif in r
There are several ways to produce a gif on R. If you want to transform gif images right on your computer, you will need to imagemagick. I show here an example using the package magick and the…
-
5
votes2
answers1750
viewsA: How to create a for in R with the indexes of a data frame
Complementing @Marcus-Nunes' excellent response to get the indices automatically from your data.frame, you can use the function row.names(): dato <- as.data.frame(matrix(1:64, 8, 8, T))[-3, ] #…
-
2
votes1
answer114
viewsA: Error loading average of a column
# para que os resultados sejam reproduzíveis set.seed(42) # gerar os dados x <- rnorm(10) x # [1] 1.37095845 -0.56469817 0.36312841 0.63286260 0.40426832 -0.10612452 # [7] 1.51152200 -0.09465904…
ranswered Willian Vieira 3,675 -
4
votes1
answer46
viewsA: How to parallelize a sapply with table
The problem is that the object dfteste is present in only two 4 environments created by makeCluster(). That is, you create the object in the current environment, then create another 3 environments…
-
5
votes2
answers221
viewsA: Create a vector with the Levels of a factor in r
You can use the function unique(): x <- as.factor(rep(1:13, 4)) x # [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 # [26] 13 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 #…
-
4
votes3
answers10243
viewsA: Insert author and image description. Latex
You can use the package caption and then use \caption{} as many times as you want. To determine the position of the legend will follow the order in which you write the code. So, for a legend above…
latexanswered Willian Vieira 3,675 -
6
votes2
answers4592
viewsA: How do you turn a comma number into an R?
When reading the csv file data, use the argument dec to specify the decimal separator: read.csv('dados.csv', dec = ",")
ranswered Willian Vieira 3,675