matching strings regex exact match - r

This thread follows on from this answered qestion: Matching strings loop over multiple columns
I opened a new thread as I would like to make an update to flag for exact matches only..
I have a table of key words in separate colums as follows:
#codes table
codes <- structure(
list(
Support = structure(
c(2L, 3L, NA),
.Label = c("",
"help", "questions"),
class = "factor"
),
Online = structure(
c(1L,
3L, 2L),
.Label = c("activities", "discussion board", "quiz", "sy"),
class = "factor"
),
Resources = structure(
c(3L, 2L, NA),
.Label = c("", "pdf",
"textbook"),
class = "factor"
)
),
row.names = c(NA,-3L),
class = "data.frame"
)
I also have a comments table structured as follows:
#comments table
comments <- structure(
list(
SurveyID = structure(
1:5,
.Label = c("ID_1", "ID_2",
"ID_3", "ID_4", "ID_5"),
class = "factor"
),
Open_comments = structure(
c(2L,
4L, 3L, 5L, 1L),
.Label = c(
"I could never get the pdf to download",
"I could never get the system to work",
"I didn’t get the help I needed on time",
"my questions went unanswered",
"staying motivated to get through the textbook",
"there wasn’t enough engagement in the discussion board"
),
class = "factor"
)
),
class = "data.frame",
row.names = c(NA,-5L)
)
What I am trying to do:
Search for an exact match keyword. The following working code has been provided by #Len Greski and #Ronak Shah from the previous thread (with huge thanks to both):
resultsList <- lapply(1:ncol(codes),function(x){
y <- stri_detect_regex(comments$Open_comments,paste(codes[[x]],collapse = "|"))
ifelse(y == TRUE,1,0)
})
results <- as.data.frame(do.call(cbind,resultsList))
colnames(results) <- colnames(codes)
mergedData <- cbind(comments,results)
mergedData
and
comments[names(codes)] <- lapply(codes, function(x)
+(grepl(paste0(na.omit(x), collapse = "|"), comments$Open_comments)))
Both work great but I have come across a snag and now need to match the keywords exactly. As per the example tables above, if I have a keyword "sy", the code will flag any comment with the word "system". I would modify either of the above pieces of code to flag the comment where only "sy" exact match is present.
Many thanks

Related

Filter two tables with crosstalk

I am creating a Flexdashboard in R. I want the dashboard to contains both a table and a series of visualizations, that would be filtered through inputs.
As I need to deliver a dashboard locally (without a server running in the background), I am unable to use Shiny, hence I rely on crosstalk.
I know that the crosstalk package provides limited functionality in the front-end. For instance, the documentation says that you can't aggregate the SharedData object.
Nonetheless, I am not clear if I can use the same inputs to filter two different dataframes.
For example, lets say I have:
Dataframe One: Contains original data
df1 <- structure(list(owner = structure(c(1L, 2L, 2L, 2L, 2L), .Label = c("John",
"Mark"), class = "factor"), hp = c(250, 120, 250, 100, 110),
car = structure(c(2L, 2L, 2L, 1L, 1L), .Label = c("benz",
"bmw"), class = "factor"), id = structure(1:5, .Label = c("car1",
"car2", "car3", "car4", "car5"), class = "factor")), .Names = c("owner",
"hp", "car", "id"), row.names = c(NA, -5L), class = "data.frame")
Dataframe Two: Contains aggregated data
df2 <- structure(list(car = structure(c(1L, 2L, 1L, 2L), .Label = c("benz",
+ "bmw"), class = "factor"), owner = structure(c(1L, 1L, 2L, 2L
+ ), .Label = c("John", "Mark"), class = "factor"), freq = c(0L,
+ 1L, 2L, 2L)), .Names = c("car", "owner", "freq"), row.names = c(NA,
+ -4L), class = "data.frame")
These two dataframes contain columns with identical values - car and owner. As well as, additional columns too.
I could create two different objects:
library(crosstalk)
shared_df1 <- SharedData$new(df1)
shared_df2 <- SharedData$new(df2)
and than:
filter_select("owner", "Car owner:", shared_df1, ~ owner)
filter_select("owner", "Car owner:", shared_df2, ~ owner)
However, that would mean that the user will need to fill inputs that are essentially identical, twice. Also, if the table is large, this would double the size of the memory needed to use the dashboard.
Is it possible to work around this problem in crosstalk?
Ah I recently ran into this too, there is another argument to SharedData$new(..., group = )! The group argument seems to do the trick. I found out by accident when I had two dataframes and used the group =.
If you make a sharedData object, it will include
a dataframe
a key to select rows by - preferably unique, but not necessarily.
a group name
What I think happens is that crosstalk filters the sharedData by the key - for all sharedData objects in the same group! So as long as two dataframes use the same key, you should be able to filter them together in one group.
This should work for your example.
---
title: "blabla"
output:
flexdashboard::flex_dashboard:
orientation: rows
social: menu
source_code: embed
theme: cerulean
---
```{r}
library(plotly)
library(crosstalk)
library(tidyverse)
```
```{r Make dataset}
df1 <- structure(list(owner = structure(c(1L, 2L, 2L, 2L, 2L), .Label = c("John", "Mark"), class = "factor"), hp = c(250, 120, 250, 100, 110), car = structure(c(2L, 2L, 2L, 1L, 1L), .Label = c("benz", "bmw"), class = "factor"), id = structure(1:5, .Label = c("car1", "car2", "car3", "car4", "car5"), class = "factor")), .Names = c("owner", "hp", "car", "id"), row.names = c(NA, -5L), class = "data.frame")
df2 <- structure(list(car = structure(c(1L, 2L, 1L, 2L), .Label = c("benz",
"bmw"), class = "factor"), owner = structure(c(1L, 1L, 2L, 2L
), .Label = c("John", "Mark"), class = "factor"), freq = c(0L,
1L, 2L, 2L)), .Names = c("car", "owner", "freq"), row.names = c(NA,
-4L), class = "data.frame")
```
#
##
### Filters
```{r}
library(crosstalk)
# Notice the 'group = ' argument - this does the trick!
shared_df1 <- SharedData$new(df1, ~owner, group = "Choose owner")
shared_df2 <- SharedData$new(df2, ~owner, group = "Choose owner")
filter_select("owner", "Car owner:", shared_df1, ~owner)
# You don't need this second filter now
# filter_select("owner", "Car owner:", shared_df2, ~ owner)
```
### Plot1 with plotly
```{r}
plot_ly(shared_df1, x = ~id, y = ~hp, color = ~owner) %>% add_markers() %>% highlight("plotly_click")
```
### Plots with plotly
```{r}
plot_ly(shared_df2, x = ~owner, y = ~freq, color = ~car) %>% group_by(owner) %>% add_bars()
```
##
### Dataframe 1
```{r}
DT::datatable(shared_df1)
```
### Dataframe 2
```{r}
DT::datatable(shared_df2)
```
I spent some time on this by trying to extract data from plot_ly() using plotly_data() without luck until I figured out the answer. That's why there's some very simple plots with plotly.
Recently, I've also wanted to use one filter to filter 2 visualizations.
Brief description of my situation
I've wanted to use one filter to filter a boxplot and a table.
Source data has been a data frame. I've wanted to use some of variables for the boxplot and also calculate some statistics (like mean, standard deviation, mode, number of records).
Functions I've needed to use to display results: plotly::plot_ly(), DT::datatable(), crosstalk::bscols().
I've found out that there are 3 key information to solve this situation
Key 1) It's necessary to correctly create shared data.
In my case, I've had to use crosstalk::SharedData$new() twice.
Correct shared data, to be used as source for visualizations, can be used if firstly keys 2 and 3 are fulfilled.
Key 2) When creating shared data, use the same group argument as "Lodewic Van Twillert" explained on 16 Mar 2018.
Key 3) Ensure that all SharedData instances refer conceptually to the same data points, and share the same keys.
Start with ensuring that a data frame has row names even if row names are character vector with numbers (like "1", "2", ...).
Used literature for this key 3: https://rstudio.github.io/crosstalk/using.html. (I suggest to mainly read subtitle "Grouping".)
Summary of steps I've used to fulfill key information from above
Key 3) This one could be tricky in order to fulfill relevant conditions of key 3 above.
The approach I've chosen creates one table containing all data and this table (data frame) will be used to create both shared data.
I've applied data manipulations to original data frame (risk_scores_df) so now this data has a new column.
I've created a new data frame with statistics.
I've joined both data frames using
risk_scores_df <- dplyr::left_join... so now the original data frame contains all prepared data.
I've run print(rownames(risk_scores_df)) to ensure that my updated data frame has row names.
Now, I've had one data frame containing all data (needed for both visualizations) that fulfill conditions of information of key 3 above.
Key 2) I've simply added group = "sd1" in both crosstalk::SharedData$new()
Key 1) This one could be also tricky if a wrong approach is chosen.
Here, the key to create correct shared data instances is to use that one table with all data and choose only rows and columns needed for a relevant shared data.
Example - in my case, I've run codes in Option 1 to create two shared data instances, but also Option 2 is possible.
Option 1 (choosing of only needed rows and columns is in crosstalk::SharedData$new())
rs_df_sd1 <- crosstalk::SharedData$new(
risk_scores_df[, c(1, 2, 5)],
group = "sd1"
)
rs_df_sd1a <- crosstalk::SharedData$new(
risk_scores_df[risk_scores_df$NumRecords > 0 &
is.na(risk_scores_df$NumRecords) == F,
c(1, 6:11)],
group = "sd1"
)
Option 2 (choosing of only needed rows and columns is in additional variables)
sd1 <- risk_scores_df[, c(1, 2, 5)]
sd1a <- risk_scores_df[risk_scores_df$NumRecords > 0 &
is.na(risk_scores_df$NumRecords) == F,
c(1, 6:11)]
rs_df_sd1 <- crosstalk::SharedData$new(sd1, group = "sd1")
rs_df_sd1a <- crosstalk::SharedData$new(sd1a, group = "sd1")
Completing the solution
At this point I've created shared data instances rs_df_sd1 and rs_df_sd1a that can be used as main sources for visualizations that will be filtered using crosstalk::bscols().
Brief example:
box_n_jitter_chart1 <- plotly::plot_ly(rs_df_sd1) %>% add_trace(...
DT_table1 <- DT::datatable(rs_df_sd1a)
crosstalk::bscols(
widths = c(6, 12, NA),
crosstalk::filter_select(
id = "idAvgRisk",
label = "Account",
sharedData = rs_df_sd1,
group = ~Account,
multiple = F
),
box_n_jitter_chart1,
DT_table1
)
Note: DT::datatable() can also use rs_df_sd1a$data() and cells = list(values = base::rbind(... (see that cells = ... is used; see more about using cells e.g. at https://plotly.com/r/reference/table/) but because method data() is used (see more e.g. at https://rdrr.io/cran/crosstalk/man/SharedData.html#method-data) then it will not work with crosstalk::bscols.

Is there a limit to the number of levels in R?

I am wondering if there is a limitation on the number of levels for a factor?
I am trying to restructure some curriculums from Xing. The selectable industries are around 135 different ones.
My code looks like that, as I mentioned there are 135 different industries in my actual code.
companyIndustryLevels <- c("","ACADEMIA", "ACCOUNTING", "AEROSPACE")
levels(samples[[1]]$Industry) <- companyIndustryLevels
The following combinations work fine and are selectable when filtering the list.
genderLevels <- c("M","F")
companySizeLevels <- c("","1","1-10","11-50","51-200","201-500","501-1000","1001-5000","5001-10000","10001+")
levels(samples[[1]]$Gender) <- genderLevels
levels(samples[[1]]$CompanySize) <- companySizeLevels
So the problem is, that when viewing the list, the industry column only shows factor with 1 level, not with 135 levels.
EDIT:
I am using RStudio Version 11.1.383 and R Version 3.4.3.
As you can see in the reproductable example below the other columns like "Gender", "Beschäftigungsart", "Position", "Unternehmensgroesse" also got levels.
When selecting the Filter in the View Window in RStudio I am able to filter all of the columns by their levels, except the "Industrie" column.
View(structure(
list(
ID = 1,
Gender = structure(1L, .Label = c("M",
"F"), class = "factor"),
Bildungseinrichtungen = structure(1L, .Label = "", class = "factor"),
Abschluss = structure(1L, .Label = "", class = "factor"),
Studienfach = structure(1L, .Label = "", class = "factor"),
Beschäftigungsart = structure(
1L,
.Label = c(
"",
"FULL_TIME_EMPLOYEE",
"PART_TIME_EMPLOYEE",
"INTERN",
"FREELANCER",
"OWNER",
"PARTNER",
"BOARD_MEMBER",
"VOLUNTEER"
),
class = "factor"
),
Station.Start = NA,
Station.Ende = NA,
Bezeichnung = NA,
Position = structure(
1L,
.Label = c(
"",
"STUDENT_INTERN",
"ENTRY_LEVEL",
"PROFESSIONAL_EXPERIENCED",
"MANAGER_SUPERVISOR",
"EXECUTIVE",
"SENIOR_EXECUTIVE"
),
class = "factor"
),
Unternehmen = structure(1L, .Label = "AMA", class = "factor"),
Unternehmensgroesse = structure(
1L,
.Label = c(
"",
"1",
"1-10",
"11-50",
"51-200",
"201-500",
"501-1000",
"1001-5000",
"5001-10000",
"10001+"
),
class = "factor"
),
Industrie = structure(
1L,
.Label = c(
"ACADEMIA",
"ACCOUNTING",
"AEROSPACE",
"AGRICULTURE",
"AIRLINES",
"ALTERNATIVE_MEDICINE",
"APPAREL_AND_FASHION",
"ARCHITECTURE_AND_PLANNING",
"ARTS_AND_CRAFTS",
"AUTOMOTIVE",
"BANKING",
"BIOTECHNOLOGY",
"BROADCAST_MEDIA",
"BUILDING_MATERIALS",
"BUSINESS_SUPPLIES_AND_EQUIPMENT",
"CHEMICALS",
"CIVIC_AND_SOCIAL_ORGANIZATIONS",
"CIVIL_ENGINEERING",
"CIVIL_SERVICE",
"COMPOSITES",
"COMPUTER_AND_NETWORK_SECURITY",
"COMPUTER_GAMES",
"COMPUTER_HARDWARE",
"COMPUTER_NETWORKING",
"COMPUTER_SOFTWARE",
"CONSTRUCTION",
"CONSULTING",
"CONSUMER_ELECTRONICS",
"CONSUMER_GOODS",
"CONSUMER_SERVICES",
"COSMETICS",
"DAYCARE",
"DEFENSE_MILITARY",
"DESIGN",
"EDUCATION",
"ELEARNING",
"ELECTRICAL_ENGINEERING",
"ENERGY",
"ENTERTAINMENT",
"ENVIRONMENTAL_SERVICES",
"EVENTS_SERVICES",
"FACILITIES_SERVICES",
"FACILITY_MANAGEMENT",
"FINANCIAL_SERVICES",
"FISHERY",
"FOOD",
"FUNDRAISING",
"FURNITURE",
"GARDENING_LANDSCAPING",
"GEOLOGY",
"GLASS_AND_CERAMICS",
"GRAPHIC_DESIGN",
"HEALTH_AND_FITNESS",
"HOSPITALITY",
"HUMAN_RESOURCES",
"IMPORT_AND_EXPORT",
"INDUSTRIAL_AUTOMATION",
"INFORMATION_SERVICES",
"INFORMATION_TECHNOLOGY_AND_SERVICES",
"INSURANCE",
"INTERNATIONAL_AFFAIRS",
"INTERNATIONAL_TRADE_AND_DEVELOPMENT",
"INTERNET",
"INVESTMENT_BANKING",
"JOURNALISM",
"LEGAL_SERVICES",
"LEISURE_TRAVEL_AND_TOURISM",
"LIBRARIES",
"LOGISTICS_AND_SUPPLY_CHAIN",
"LUXURY_GOODS_AND_JEWELRY",
"MACHINERY",
"MANAGEMENT_CONSULTING",
"MARITIME",
"MARKETING_AND_ADVERTISING",
"MARKET_RESEARCH",
"MECHANICAL_INDUSTRIAL_ENGINEERING",
"MEDIA_PRODUCTION",
"MEDICAL_DEVICES",
"MEDICAL_SERVICES",
"MEDICINAL_PRODUCTS",
"METAL_METALWORKING",
"METROLOGY_CONTROL_ENGINEERING",
"MINING_AND_METALS",
"MOTION_PICTURES",
"MUSEUMS_AND_CULTURAL_INSTITUTIONS",
"MUSIC",
"NANOTECHNOLOGY",
"NON_PROFIT_ORGANIZATION",
"NURSING_AND_PERSONAL_CARE",
"OIL_AND_ENERGY",
"ONLINE_MEDIA",
"OTHERS",
"OUTSOURCING_OFFSHORING",
"PACKAGING_AND_CONTAINERS",
"PAPER_AND_FOREST_PRODUCTS",
"PHOTOGRAPHY",
"PLASTICS",
"POLITICS",
"PRINTING",
"PRINT_MEDIA",
"PROCESS_MANAGEMENT",
"PROFESSIONAL_TRAINING_AND_COACHING",
"PSYCHOLOGY_PSYCHOTHERAPY",
"PUBLIC_HEALTH",
"PUBLIC_RELATIONS_AND_COMMUNICATIONS",
"PUBLISHING",
"RAILROAD",
"REAL_ESTATE",
"RECREATIONAL_FACILITIES_AND_SERVICES",
"RECYCLING_AND_WASTE_MANAGEMENT",
"RENEWABLES_AND_ENVIRONMENT",
"RESEARCH",
"RESTAURANTS_AND_FOOD_SERVICE",
"RETAIL",
"SECURITY_AND_INVESTIGATIONS",
"SEMICONDUCTORS",
"SHIPBUILDING",
"SPORTS",
"STAFFING_AND_RECRUITING",
"TAX_ACCOUNTANCY_AUDITING",
"TELECOMMUNICATION",
"TEXTILES",
"THEATER_STAGE_CINEMA",
"TIMBER",
"TRAFFIC_ENGINEERING",
"TRANSLATION_AND_LOCALIZATION",
"TRANSPORT",
"VENTURE_CAPITAL_AND_PRIVATE_EQUITY",
"VETERINARY",
"WELFARE_AND_COMMUNITY_HEALTH",
"WHOLESALE",
"WINE_AND_SPIRITS",
"WRITING_AND_EDITING",
"PHARMACEUTICALS"
),
class = "factor"
)
),
.Names = c(
"ID",
"Gender",
"Bildungseinrichtungen",
"Abschluss",
"Studienfach",
"Beschäftigungsart",
"Station.Start",
"Station.Ende",
"Bezeichnung",
"Position",
"Unternehmen",
"Unternehmensgroesse",
"Industrie"
),
row.names = 1L,
class = "data.frame"
))
It seems as if the Filtering option in RStudio's Data Viewer (View()) offers a drop down menu for a factor, when its number of levels (nlevels()) is less than 65. Otherwise it defaults to a search field:
df <- data.frame(x=as.factor(1:64))
View(df)
# "filter" yields a drop down menu
df <- data.frame(x=as.factor(1:65))
View(df)
# "filter" yields a search field
RStudio.Version()$version
# [1] ‘1.0.143’
Note that this has nothing to do with R itself, as already mentioned in the comments.

How to use ifelse and paste functions

I am learning the use of the ifelse function from Zuur et al (2009) A Beginners guide to R. In one exercise, there is a data frame called Owls which contains data about about 27 nests and two night of observations.
structure(list(Nest = structure(c(1L, 1L, 1L, 1L), .Label = "AutavauxTV", class = "factor"),
FoodTreatment = structure(c(1L, 2L, 1L, 1L), .Label = c("Deprived",
"Satiated"), class = "factor"), SexParent = structure(c(1L,
1L, 1L, 1L), .Label = "Male", class = "factor"), ArrivalTime = c(22.25,
22.38, 22.53, 22.56), SiblingNegotiation = c(4L, 0L, 2L,
2L), BroodSize = c(5L, 5L, 5L, 5L), NegPerChick = c(0.8,
0, 0.4, 0.4)), .Names = c("Nest", "FoodTreatment", "SexParent",
"ArrivalTime", "SiblingNegotiation", "BroodSize", "NegPerChick"
), row.names = c(NA, 4L), class = "data.frame")
The two nights differed as to the feeding regime (satiated or deprived) and are indicated in the Foodregime variable. The task is to use ifelse and past functions that make a new categorical variable that defines observations from a single night at a particular nest.
In the solutions the following code is suggested:
Owls <- read.table(file = "Owls.txt", header = TRUE, dec = ".")
ifelse(Owls$FoodTreatment == "Satiated", Owls$NestNight <- paste(Owls$Nest, "1",sep = "_"), Owls$NestNight <- paste(Owls$Nest, "2",sep = "_"))
and apparently it creates a new variable with values the endings of which vary ("-1" or "-2")
however when I call the original dataframe, all "-1" endings in the NestNight variable disappears and are turned to "-2."
Why does this happen? Did the authors miss something from the code or it's me who is not getting it?
Many thanks
EDIT: Sorry, I wanted to give a reproducible example by copying my data using dput but it did not work. If you can let me know how I can correct it so that it appears properly, I'd be grateful too!
Solution
If you do the assignment outside the ifelse structure, it works:
Owls$NestNight <- ifelse(Owls$FoodTreatment == "Satiated",
paste(Owls$Nest, "1",sep = ""),
paste(Owls$Nest, "2",sep = ""))
Explanation
What happens in your case is simply if you would execute the following two lines:
Owls$NestNight <- paste(Owls$Nest, "1",sep = "")
Owls$NestNight <- paste(Owls$Nest, "2",sep = "")
You first assign paste(Owls$Nest, "1",sep = "") to Owls$NestNight and then you reassign paste(Owls$Nest, "2",sep = "") to it. The ifelse is not affected by this, but you don't assign it's result to any variable.
Maybe it is more clear if you test this simple code:
c(a <- 1:5, a <- 6:10) #c is your ifelse, a is your Owls$NestNight
a #[1] 6 7 8 9 10

Copy files (and existing folder structures) to new location using dataframe

I have a dataframe (df):
df = structure(list(site = c(989L, 989L, 990L, 990L), filename = structure(1:4, .Label = c("989_1.csv", "989_5.csv", "990_2.csv", "990_9.csv"), class = "factor"), sourceA = structure(1:4, .Label = c("FolderA/989/989_1.csv", "FolderA/989/989_5.csv", "FolderA/990/990_2.csv", "FolderA/990/990_9.csv" ), class = "factor"), destination = structure(c(3L, 1L, 4L, 2L ), .Label = c("FolderB/989/989_5.csv", "FolderB/990/990_9.csv", "FolderC/989/989_1.csv", "FolderD/990/990_2.csv"), class = "factor")), .Names = c("site",
"filename", "sourceA", "destination"), class = "data.frame", row.names = c(NA,
-4L))
'FolderA' has a series of subfolders containing a number of files. I wish to copy subsets of these files to other folders (shown here as 'destination'). Note: 1) the destination varies from file to file, and 2) the primary folders (FolderB,FolderC,and FolderD) exist, but the subfolders do not (e.g., FolderC/989/).
I believe my solution may involve the file.copy() function, but I am having no success.
file.copy(df$sourceA, df$destination)
results in
Error in file.exists(from) : invalid 'file' argument
Ideas?
Edit: using column name 'source' was causing problems - changed to 'sourceA'.
I think it's because the class of df$sourceA is 'factor' and copy.file wants a 'character'.

prop.table doesn't work in a for-loop?

This may be a very simple question, but I don't see how to answer it.
I have the following reproducible code, where I have two small dataframes that I use to calculate a percentage value based on each column total:
#dataframe x
x <- structure(list(PROV = structure(c(1L, 1L), .Label = "AG", class = "factor"),
APT = structure(1:2, .Label = c("AAA", "BBB"), class = "factor"),
PAX.2013 = c(5L, 4L), PAX.2014 = c(4L, 2L), PAX.2015 = c(4L,0L)),
.Names = c("PROV", "APT", "PAX.2013", "PAX.2014", "PAX.2015"),
row.names = 1:2, class = "data.frame")
#dataframe y
y <- structure(list(PROV = structure(c(1L, 1L), .Label = "AQ", class = "factor"),
APT = structure(1:2, .Label = c("CCC", "AAA"), class = "factor"),
PAX.2013 = c(3L, 7L), PAX.2014 = c(2L, 1L), PAX.2015 = c(0L,3L)),
.Names = c("PROV", "APT", "PAX.2013", "PAX.2014", "PAX.2015"),
row.names = 1:2, class = "data.frame")
#list z (with x and y)
z <- list(x,y)
#percentage value of x and y based on columns total
round(prop.table(as.matrix(z[[1]][3:5]), margin = 2)*100,1)
round(prop.table(as.matrix(z[[2]][3:5]), margin = 2)*100,1)
as you can see, it works just fine.
Now I want to automate for all the list, but I can't figure out how to get the results. This is my simple code:
#for-loop that is not working
for (i in length(z))
{round(prop.table(as.matrix(z[[i]][3:5]), margin = 2)*100,1)}
You have two problems.
First, you have not put a range into your for loop so you are just trying to iterate over a single number and second, you are not assigning your result anywhere on each iteration.
Use 1:length(z) to define a range. Then assign the results to a variable.
This would work:
my_list <- list()
for (i in 1:length(z)){
my_list[[i]] <- round(prop.table(as.matrix(z[[i]][3:5]),
margin = 2)*100,1)
}
my_list
But it would be more efficient and idiomatic to use lapply:
lapply(1:length(z),
function(x) round(prop.table(as.matrix(z[[x]][3:5]), margin = 2)*100,1))
Barring discussions whether for-loops is the best approach, you had two issues. One, your for loop only iterates over 2 (which is length(z)) instead of 1:2. Two, you need to do something with the round(....) statement. In this solution, I added a print statement.
for (i in 1:length(z)){
print(round(prop.table(as.matrix(z[[i]][3:5]), margin = 2)*100,1))
}

Resources