Generate Data sets of same Random Values in R Programming - set.seed() Function - GeeksforGeeks (2024)

Last Updated : 28 Nov, 2023

Improve

Improve

Like Article

Like

Save

Report

In this article, we will discuss how we Generate Data sets of the same Random Values in the R Programming Language using set.seed() Function.

What is to set seed in R?

set.seed()function inR Programming Languageis used to create random numbers that can be reproduced. It helps in creating the same random numbers each time a random function is called. This helps in creating repeatable data sets for analysis.

Syntax: set.seed(n)

Parameters:

n: seeds for repeatable data sets

Create Random Numbers without a set.seed() function in R

Output:

 [1] 0.38984324 -0.62124058 -2.21469989 1.12493092 -0.04493361 [6] -0.01619026 0.94383621 0.82122120 0.59390132 0.91897737

Why set.seed() is required

In R, the set.seed() function is not mandatory for all analyses. However, it is recommended to use it in some instances. There are various reasons why using set.seed() becomes advantageous.

  • Reproducibility: Seed setting guarantees that the sequence of random numbers created by our code will remain constant across different runs. This is necessary when we want other people to reproduce our results or even if we need to reproduce our own findings at a later date. Without a set seed, the randomness introduced by R’s random number generator could lead to different results each time the code is executed.
  • Comparisons and Testing: To ensure that any observed differences are not due to random chance, a fixed seed should be present when comparing algorithms, models or methods among others.
  • Debugging: While debugging our code, having a fixed seed can simplify the process. Absence of a seed may lead to inconsistent results which may complicate the process of identifying errors or unexpected behaviors in our code.
  • Communication and Documentation: our code becomes more transparent once we employ set.seed(). By specifying the seed when sharing the code with others they can always get exactly the same results as ours.

R program to create repeatable data sets

R

# R program to create repeatable data sets

# Setting seeds

set.seed(10)

# Creating data set of random values

x <- rnorm(15)

paste('The random values of x')

x

# Setting seed again for another data set

set.seed(10)

# Creating another data set

y <- rnorm(15)

paste('The random values of y')

y

# Checking if both are equal

paste('The identical values of x and y')

identical(x, y)

Output:

[1] "The random values of x" [1] 0.01874617 -0.18425254 -1.37133055 -0.59916772 0.29454513 [6] 0.38979430 -1.20807618 -0.36367602 -1.62667268 -0.25647839[11] 1.10177950 0.75578151 -0.23823356 0.98744470 0.74139013[1] "The random values of y" [1] 0.01874617 -0.18425254 -1.37133055 -0.59916772 0.29454513 [6] 0.38979430 -1.20807618 -0.36367602 -1.62667268 -0.25647839[11] 1.10177950 0.75578151 -0.23823356 0.98744470 0.74139013[1] "The identical values of x and y"[1] TRUE

R program to create repeatable data sets

R

# R program to create repeatable data sets

# Setting seeds

set.seed(10)

# Creating data set of random values

x <- rexp(15)

paste('The random values of x')

x

# Setting seed again for another data set

set.seed(10)

# Creating another data set

y <- rexp(15)

paste('The random values of y')

y

# Checking if both are equal

paste('The equal values of x and y')

identical(x, y)

Output:

 [1] "The random values of x"

[1] 0.01495641 0.92022120 0.75215894 1.57504185 0.23165862 1.08667300
[7] 2.32762287 0.72912382 1.28831010 0.67226829 0.42652979 1.11542195
[13] 1.31654707 0.41329383 0.67657533

[1] "The random values of y"

[1] 0.01495641 0.92022120 0.75215894 1.57504185 0.23165862 1.08667300
[7] 2.32762287 0.72912382 1.28831010 0.67226829 0.42652979 1.11542195
[13] 1.31654707 0.41329383 0.67657533

[1] "The equal values of x and y"

[1] TRUE



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Generate Data sets of same Random Values in R Programming - set.seed() Function - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 5936

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.