首页 > 解决方案 > 添加一列以按月计算 non.na 的出现次数 (dplyr)

问题描述

我正在尝试在变量 x 下创建一个计算出现次数(即 non.na)的新变量。我的数据集中的每一行都代表一个职位发布,我想计算每月提到主干专业/学位作为工作要求的职位发布数量。

我创建了一个变量“stem_mention”,它计算整个数据集中的所有工作提及,如下所示:

df2$stem_mention= NA #creating empty column

#placing the possible levels into a vector
stem_mention= c("chemical engineering", "electrical engineering", "physics", "biology", "engineering")

#for each value in stem_mention, if description has that value assign the new column one of the 4 numbers
for(i in stem_mention){
  value = grepl(i, df2$description, ignore.case=TRUE)
  df2$stem_mention[which(value)] = (1:5)[stem_mention==i]}
table(df2$stem_mention)
1  2  4  5 
49  9  4 20

但是,我正在尝试为变量“stem_mention”创建一个计算 non.NAs 的列,然后将其除以给定月份发布的工作总数,得到如下所示的内容:

使用下面提出的解决方案,我这样做了:

df2 %>%
group_by(month) %>%
filter(!is.na(stem)) %>%
summarize(stem_month = sum(stem))

产生:

month
<chr>
stem_month
<int>
April_2021  19          
Dec_2020    35          
Feb_2021    23          
March_2021  46          
May_2021    13          
Nov_2020    47

但是,我正在尝试按月创建一个总职位“jobs_per_month”,该变量允许我执行以下操作:

df2 <- 
  group_by(month) %>%
  transform(df2, share_stem_month = stem_monthly_mention/ jobs_per_month)
share_stem_month     month     jobs_per_month stem_monthly_mention
9%                  May_2021       267           24
10%                 April_2021     290           29

可重现的数据ex

head(Jobs_Glassdoor_Nov_Dec2020_Feb_March_April_May2021, 5)[, c('month', 'nationality', 'posted_date')]
month
<chr>
stem_mention
<int>
posted_date
<chr>
Nov_2020    NA  44172.197916666664      
Nov_2020    6   44154.094444444447      
Nov_2020    NA  44164.156944444447      
Nov_2020    NA  44147.370138888888      
Nov_2020    NA  44173.06527777778

标签: rdplyrtidyverse

解决方案


查看@Ronak 提到的数据片段会很有帮助,但如果我正确理解您的问题,您需要组合group_by,filtersummarize

library(dplyr)
df2 %>%
group_by(month) %>%
filter(!is.na(stem_share)) %>%
summarize(summ_by_month = sum(step_share))

这能满足你的需要吗?如果您想为每个月的非 NA 总计向现有数据集添加一个新变量,我认为您只需将上述内容分配给df2$non_nas_by_month或类似的东西。如果这不起作用,请告诉我

清理数据片段

df2 <- structure(
  list(
    description = c("Minimum Clearance Required to Start:  \r\n\r\nNot Applicable/None  \r\n\r\nJob Description:  \r\n\r\nAre you invigorated by digging for new and different solutions?  \r\n\r\nYou'll find an open playing field for your open mind and \"adventurous\" spirit\r\nwhen it comes to getting to the bottom of interesting challenges. We need\r\ncritical and creative thinkers like you -- managers who are stimulated by\r\nvariety, adapt to change, and set an inspiring example for their teams. We\r\ncouldn't be the leaders we are without leaders like you.  \r\n\r\nPOSITION OVERVIEW  \r\n\r\nPMO Manager is a highly visible cross-function role leading the PMO department\r\nand serving as a focal point for project support to senior leaders. This\r\nindividual will develop and manage best practices for project management\r\nacross the project lifecycle, and will ensure delivery of projects against\r\ngoals, schedule, and budget. The Project Manager shall prepare and oversee\r\npreparation of technical and commercial proposals, including man-hour\r\nestimates. Must have experience in managing multiple large sized projects.\r\nAble to communicate with clients and in-house staff to bring projects in at\r\ncost.  \r\n\r\nSPECIFIC RESPONSIBILITIES\r\n\r\n* Partner with senior leaders across the business to proactively identify and define projects aligned to the company's strategic priorities and vision\r\n* Manage the PMO department's portfolio of projects, evaluating and prioritizing project requests, and assigning project management resources\r\n* Support project scoping, ensure resource allocation and cross-functional collaboration, identify and mitigate competing priorities, assess business readiness, and evaluate effectiveness of change management and adoption strategies.\r\n* Expert level knowledge of project and change management and associated methodologies, techniques, processes and approaches.\r\n* Budget, cost and profitability management skills\r\n* Knowledge of resource management tools\r\n* Ability to mentor, coach and effectively transfer expertise to others\r\n* Ability to build a strong network and relationships at executive levels with technology and solutions, customers and vendor groups\r\n* Ensures a clear and consistent approach is followed and is aligned with corporate objectives\r\n* Acts as primary communication linkage between business and customers regarding contracts and project's progress\r\n* Attend/Chair meetings as required to resolve issues and provide status updates\r\n* Proactively engage with Directors and Senior Managers to identify opportunities for business improvements\r\n\r\nQUALIFICATION :\r\n\r\n* BBS/BA degree in Engineering from Western University along with 20 years or more years of related work experience in the field of Buildings, infrastructure, and real estate as PMO and construction consultant. Experience on large construction projects with leading multinational consultant companies. Must have worked as project lead in last 10 years.\r\n* Certified Project Management Professional (PMP) or have a management level certification\r\n* Business Acumen (Business Strategy, Contract Management)\r\n* Leadership (Inclusiveness, Critical Thinking)\r\n* Technical Project Management (Professional Execution within a formal framework)\r\n* Demonstrated ability to lead and influence a matrix-organized team through the lifecycle of a project\r\n* Strong interpersonal skills with the ability to effectively communicate with all stakeholders.\r\n\r\nWe foster great, team-spirited collaborations  \r\n\r\nWe're truly a community that's open for everyone to participate in making an\r\nimpact. If you manage with insight and ideas, you'll feel at home here. As a\r\nteam-based culture, we look for leaders who can inspire their work group to\r\nwork well together, respect differing opinions, listen actively, and be\r\nexpressive with their own ideas. We welcome diversity and look forward to\r\nincluding people of all backgrounds into our stimulating collaborative process\r\nfor personal and professional growth", 
                    "Hill+Knowlton Strategies is currently seeking a Junior Account Executive to be\r\nbased in our Riyadh office (KSA), you will be a highly proactive, creative and\r\nmotivated individual, with bags of energy and an ambition to jump start your\r\ncareer in the communications industry.  \r\n\r\nFor graduates - or young professionals changing direction - this entry-level\r\nposition provides an opportunity to gain valuable experience.  \r\n\r\nAt H+K, Junior Account Executives receive training in core aspects of public\r\nrelations activity to support progression to the next level with a solid\r\nfoundation of skills and experience. The tasks of a Junior Account Executive\r\nspan the breadth of PR activity; from researching and writing creative\r\ncontent, through to social media activation, events, and lots of networking to\r\nbuild your relationships with key media and online influencers.  \r\n\r\nThe following job description details the skills and competencies required for\r\nthis level.  \r\n\r\nAt this level, you will be able to:  \r\n\r\nConsulting\r\n\r\n* Develop and demonstrate a solid understanding of core PR principles\r\n* Research and develop a basic understanding of clients' markets and competitors\r\n* Develop an understanding of the regional media landscape and begin to build a network of influencer and media contacts\r\n* Take ownership of defined tasks including media and online research, maintaining media and influencer lists, monitoring media and compiling accurate coverage reports, effectively pitching news to media, securing interviews and opportunities for clients\r\n* Assist with preparation, delivery and follow up of events, including press conferences, media/analyst/influencer briefings, social events and interviews\r\n* Support product review programmes with attention to detail on logistics and inventory\r\n* Demonstrate creativity, understanding and attention to detail through the ability to create first drafts of client-ready content, including press releases, executive briefing documents, social media calendar and content, interview transcripts/summaries and activity reports\r\n* Continue development of language skills for Arabic consultants; including expertise in originating core content for different platforms, localising materials to the Arabic language and audience, and working with the translation team to improve client-ready content\r\n* Establish familiarity with popular social media channels; how they work, their audience and purpose, the services they offer and what content is best suited to each environment\r\n* Extract information and compile reports from social tools including Sherlock, Facebook Analytics, Twitter Analytics, YouTube Analytics, LexisNexis and Sysomos\r\n* Create accurate and clear reports for all channels, such as tracker reports, conversation/topic analyses, ad campaign reports, community management and coverage reports\r\n* Actively participate in internal creative brainstorms across all agency sectors and apply creative thinking to all aspects of your work\r\n\r\nPeople\r\n\r\n* Understand the structure and roles of teams in your portfolio\r\n* Show ability to accept, understand and act on instruction from team leads\r\n* Support the work load and activities of team assistants and interns\r\n* Actively participate in team and client meetings in an appropriate manner\r\n* Provide support to the H+K internship programme through the buddy role and H+K's engagement with local universities\r\n* Act as H+K ambassador internally and externally\r\n\r\nBusiness Acumen\r\n\r\n* Build a basic understanding of H+K's business and the MENAT network\r\n* Complete Maconomy time sheets on a weekly basis - mandatory\r\n* Be familiar with H+K's social media policy and professional practices\r\n* Contribute to the external marketing activity of H+K Strategies\r\n* Be diligent in submitting expenses in a timely manner\r\n\r\nPROFESSIONAL DEVELOPMENT\r\n\r\n* Demonstrate an aptitude for public relations and grow network of media, influencer and industry contacts\r\n* Progress content development capabilities with a focus on writing skills\r\n* Implementation of day-to-day publishing work, online and traditional media\r\n* Take responsibility for part of a client or project WIP\r\n* Identify and discuss long term career goals with Line Manager\r\n* Demonstrate professional behaviour at all times\r\n\r\nQUALIFICATIONS:\r\n\r\n* University degree\r\n* Entry level to 6 months' relevant industry experience\r\n* Excellent Arabic/English written and oral communication skills\r\n* Ability to multi-task and work in a team environment\r\n* This position is open to KSA nationals only."), 
    industry = c("IT Services", "Advertising & Marketing"), 
    headquarters = c("Centreville, VA", "New York, NY"), 
    sector = c("Information Technology", "Business Services"), 
    website = c("www.parsons.com", "www.hkstrategies.com"), 
    company_size = c("10000+ Employees", "1001 to 5000 Employees"), 
    estimated_salary = c(NA, NA), 
    revenue = c("$2 to $5 billion (USD)", "Unknown / Non-Applicable"), 
    founded_year = c(1944, 1927), 
    benefits = c("{\"benefitRatingDecimal\": 3.7, \"comments\": [{\"benefitComments\": [{\"comment\": \"Health insurance premiums are slightly higher than what I'm used to in the industry, and no additional contribution to HSA if you choose a high deductible plan\"}], \"cityName\": \"San Diego\", \"createDate\": \"2020-10-07T15:33:05.147\", \"currentJob\": true, \"rating\": 4, \"stateName\": \"California\", \"userEnteredJobTitle\": \"\"}, {\"benefitComments\": [{\"comment\": \"Company wants to be an employer of choice, but benefits are very basic/borderline unsatisfactory for the market against other technology companies. \"}], \"cityName\": \"Charlotte\", \"createDate\": \"2020-11-15T15:30:03.803\", \"currentJob\": true, \"rating\": 3, \"stateName\": \"North Carolina\", \"userEnteredJobTitle\": \"\"}, {\"benefitComments\": [{\"comment\": \"health benefits are decent, matching 401k\"}], \"cityName\": \"Chesterfield\", \"createDate\": \"2020-10-06T07:47:11.610\", \"currentJob\": false, \"rating\": 5, \"stateName\": \"Missouri\", \"userEnteredJobTitle\": \"\"}], \"numReviews\": 3}", 
                 "{\"benefitRatingDecimal\": 4.3, \"comments\": [{\"benefitComments\": [{\"comment\": \"Benefits are phenomenal - vacation is generous. \"}], \"cityName\": \"Dallas\", \"createDate\": \"2020-06-14T20:41:34.503\", \"currentJob\": true, \"rating\": 5, \"stateName\": \"Texas\", \"userEnteredJobTitle\": \"\"}, {\"benefitComments\": [{\"comment\": \"bagels on pay day \"}], \"cityName\": \"Maumee\", \"createDate\": \"2020-03-29T13:22:55.093\", \"currentJob\": true, \"rating\": 3, \"stateName\": \"Ohio\", \"userEnteredJobTitle\": \"Merchandise Assistant\"}, {\"benefitComments\": [{\"comment\": \"Great company great benefits!  \"}], \"cityName\": \"Miami\", \"createDate\": \"2019-06-13T08:32:55.397\", \"currentJob\": true, \"rating\": 5, \"stateName\": \"Florida\", \"userEnteredJobTitle\": \"\"}], \"employerSummary\": {\"comment\": \"<p>At Hill+Knowlton Strategies, <strong>our first priority is our people</strong>. The best and the brightest minds in communications choose to come to work at H+K every day, and to keep them engaged, energized and working at their peak, we know we need to provide a supportive environment that allows for growth, creativity and flexibility.<br><br>Juggling work and life is always a challenge, and in a 24/7 business like public relations, the two are linked. This is why we have two categories of benefits, which we call <strong>H+K Inside</strong> and <strong>H+K Outside</strong> that make the blend of the two more manageable.<br><br>We are proud of these industry leading benefits and even more importantly, our people use them, rely on them and love them. We, of course, offer comprehensive health and dental benefits, as well as a retirement plan. But we also offer some innovative perks and policies like expanded maternity leave, a fitness subsidy, flexible work schedules, a global mentoring program and tuition reimbursement, among others.</p>\\r\\n<p><br></p>\\r\\n<p><br></p>\"}, \"numReviews\": 3}"), 
    latest_reviews = c("{\"advice\": \"Continuous the the improvement\", \"cons\": \"every thing going well in the company\", \"countHelpful\": 0, \"employerResponses\": [], \"employmentStatus\": \"REGULAR\", \"featured\": null, \"isCurrentJob\": true, \"jobTitle\": {\"text\": \"Senior Civil Engineer\"}, \"lengthOfEmployment\": 1, \"pros\": \"one of the best place to work\", \"ratingBusinessOutlook\": \"POSITIVE\", \"ratingCareerOpportunities\": 5, \"ratingCeo\": \"APPROVE\", \"ratingCompensationAndBenefits\": 4, \"ratingCultureAndValues\": 5, \"ratingOverall\": 5, \"ratingRecommendToFriend\": \"POSITIVE\", \"ratingSeniorLeadership\": 4, \"ratingWorkLifeBalance\": 3, \"reviewDateTime\": \"2019-07-21T05:01:22.277\", \"reviewId\": 28146034, \"summary\": \"Best Company\"}, {\"advice\": \"Make sure to ensure that you are not hiring more than needed staff just to let them go later on.\", \"cons\": \"If you are thinking long term this is not for you\", \"countHelpful\": 0, \"employerResponses\": [], \"employmentStatus\": \"REGULAR\", \"featured\": null, \"isCurrentJob\": false, \"jobTitle\": {\"text\": \"Project Engineer\"}, \"lengthOfEmployment\": 1, \"pros\": \"A Competitive Salary and Reasonable Package\", \"ratingBusinessOutlook\": \"POSITIVE\", \"ratingCareerOpportunities\": 4, \"ratingCeo\": \"APPROVE\", \"ratingCompensationAndBenefits\": 4, \"ratingCultureAndValues\": 4, \"ratingOverall\": 4, \"ratingRecommendToFriend\": \"POSITIVE\", \"ratingSeniorLeadership\": 4, \"ratingWorkLifeBalance\": 4, \"reviewDateTime\": \"2020-10-19T13:43:21.143\", \"reviewId\": 37343481, \"summary\": \"A Great Company\"}, {\"advice\": \"look after your employees\", \"cons\": \"lacked strong leadership and direction. employees often feel like chattle.\", \"countHelpful\": 0, \"employerResponses\": [], \"employmentStatus\": \"REGULAR\", \"featured\": null, \"isCurrentJob\": false, \"jobTitle\": {\"text\": \"Specialist\"}, \"lengthOfEmployment\": 1, \"pros\": \"Big company, big name, opportunities\", \"ratingBusinessOutlook\": \"NEUTRAL\", \"ratingCareerOpportunities\": 3, \"ratingCeo\": \"NO_OPINION\", \"ratingCompensationAndBenefits\": 4, \"ratingCultureAndValues\": 3, \"ratingOverall\": 3, \"ratingRecommendToFriend\": \"POSITIVE\", \"ratingSeniorLeadership\": 2, \"ratingWorkLifeBalance\": 3, \"reviewDateTime\": \"2019-10-08T16:26:22.660\", \"reviewId\": 29693140, \"summary\": \"Could be better\"}, {\"advice\": \"Do take care of your people not just in North America.\", \"cons\": \"Old school management and no vision for growth. Do not value employees much when it comes to out of North America. Company takes new initiatives and directions but never follow through\", \"countHelpful\": 0, \"employerResponses\": [], \"employmentStatus\": \"REGULAR\", \"featured\": null, \"isCurrentJob\": true, \"jobTitle\": {\"text\": \"Finance Director\"}, \"lengthOfEmployment\": 4, \"pros\": \"Excellent policies and procedures. Good corporate governance\", \"ratingBusinessOutlook\": \"NEGATIVE\", \"ratingCareerOpportunities\": 2, \"ratingCeo\": \"NO_OPINION\", \"ratingCompensationAndBenefits\": 2, \"ratingCultureAndValues\": 3, \"ratingOverall\": 3, \"ratingRecommendToFriend\": \"NEGATIVE\", \"ratingSeniorLeadership\": 2, \"ratingWorkLifeBalance\": 1, \"reviewDateTime\": \"2019-06-18T09:39:45.763\", \"reviewId\": 27474992, \"summary\": \"Finance, commercial and management of overall Saudi matters\"}, {\"advice\": null, \"cons\": \"There is no stability for long time\", \"countHelpful\": 2, \"employerResponses\": [], \"employmentStatus\": \"REGULAR\", \"featured\": null, \"isCurrentJob\": true, \"jobTitle\": {\"text\": \"Discipline Electrical Engineer\"}, \"lengthOfEmployment\": 2, \"pros\": \"Big consultant company that may add value to your CV\", \"ratingBusinessOutlook\": \"NEUTRAL\", \"ratingCareerOpportunities\": 3, \"ratingCeo\": \"NO_OPINION\", \"ratingCompensationAndBenefits\": 3, \"ratingCultureAndValues\": 1, \"ratingOverall\": 3, \"ratingRecommendToFriend\": \"POSITIVE\", \"ratingSeniorLeadership\": 2, \"ratingWorkLifeBalance\": 2, \"reviewDateTime\": \"2018-07-19T01:28:17.590\", \"reviewId\": 21548748, \"summary\": \"Discipline Electrical Engineer\"}", 
                       NA), 
    recommend_to_friend = c("0.74", "0.48"), 
    rating = c(3.7, 3.3), 
    posted_date = c("44172.197916666664", "44154.094444444447"), 
    company_name = c("Parsons Corporation", "Hill+Knowlton Strategies, Inc."), 
    jobtitle = c("Project Manager", "Junior Account Executive"), 
    location = c("Riyadh", "Riyadh"), 
    url = c("https://www.glassdoor.com/partner/jobListing.htm?pos=514&ao=242900&s=58&guid=0000017644315a18af43c17b07c1dc48&src=GD_JOB_AD&t=SR&vt=w&cs=1_e9d49651&cb=1607461875477&jobListingId=3763981600", 
            "https://www.glassdoor.com/partner/jobListing.htm?pos=518&ao=801693&s=58&guid=0000017644315a18af43c17b07c1dc48&src=GD_JOB_AD&t=SR&vt=w&cs=1_b48f9bdd&cb=1607461865512&jobListingId=3658944015"), 
    address = c("{\"address\": null, \"country\": \"Saudi Arabia\", \"employer\": {\"name\": \"Parsons Corporation\"}, \"locationName\": \"Riyadh\", \"postalCode\": null}",
                "{\"address\": null, \"country\": \"Saudi Arabia\", \"employer\": {\"name\": \"Hill+Knowlton Strategies, Inc.\"}, \"locationName\": \"Riyadh\", \"postalCode\": null}"), 
    complete_address = c(NA_character_, NA_character_), 
    search_url = c("https://www.glassdoor.com/Job/jobs.htm?locT=C&locId=3110290", 
                   "https://www.glassdoor.com/Job/jobs.htm?locT=C&locId=3110290"), 
    month = c("Nov_2020", "Nov_2020"), 
    adj_revenue = c("3500", "."), 
    total_jobs_industry = c(2L, 2L), 
    total_jobs_sector = 3:2,
    total_jobs_company = 1:2, 
    nationality = c(NA_integer_, NA_integer_), 
    gender_preference = c(NA_integer_, NA_integer_)), 
  row.names = c(NA, -2L), 
  groups = structure(
    list(
      company_name = c("Hill+Knowlton Strategies, Inc.", "Parsons Corporation"), 
      jobtitle = c("Junior Account Executive", "Project Manager"), 
      .rows = structure(
        list(2L, 1L), 
        ptype = integer(0), 
        class = c("vctrs_list_of", "vctrs_vctr", "list"))), 
    row.names = 1:2, 
    class = c("tbl_df", "tbl", "data.frame"), 
    .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", "data.frame"))

推荐阅读